Data¶
Image abstractions, patches, annotations, and regions of interest.
Image (Abstract Base)¶
- class medical_image.data.image.Image[source]¶
Bases:
ABCAbstract base class for medical images.
Supports lazy loading and four mutually-exclusive construction paths (file, array, source image, or empty shell). Width and height are computed properties derived from
pixel_data.shapewhen loaded, falling back to cached values before loading.The Image optionally holds a list of
Annotationobjects via aggregation – an image can exist without annotations.- pixel_data¶
Pixel values (
Noneuntil loaded).- Type:
Optional[torch.Tensor]
- annotations¶
Attached annotations (
Noneby default).- Type:
Optional[List[Annotation]]
- __init__(file_path=None, array=None, width=None, height=None, source_image=None)[source]¶
Initialise an Image via one of four construction paths.
- Parameters:
file_path (str | None) – Path to an image file. Raises
FileNotFoundErrorif it does not exist.array (ndarray | Tensor | None) – Pre-existing numpy array or torch tensor to wrap as pixel data.
width (int | None) – Explicit width hint (used before pixel data is loaded).
height (int | None) – Explicit height hint (used before pixel data is loaded).
source_image (Image | None) – Another Image to clone metadata and pixel data from.
- ensure_loaded()[source]¶
Raise
DicomDataNotLoadedErrorif pixel data has not been loaded.- Returns:
self, for method chaining.- Return type:
- pin_memory()[source]¶
Pin pixel data to page-locked memory for faster GPU transfers.
No-op if pixel data is
Noneor already pinned.- Returns:
self, for method chaining.- Return type:
- clone()[source]¶
Create a lightweight copy of this image.
Clones the pixel data tensor and shallow-copies the annotation list, but does not copy heavy objects (DICOM dataset, PIL image).
- Returns:
A new Image of the same concrete type.
- Return type:
- classmethod from_file(file_path)[source]¶
Construct an Image from a file path (lazy – does not load pixels).
- classmethod from_image(other_image)[source]¶
Construct an Image by copying metadata and pixel data from other_image.
- classmethod empty(width=None, height=None)[source]¶
Construct an empty Image shell with optional width/height hints.
- add_annotation(annotation)[source]¶
Append an annotation to this image.
Initialises the annotation list to
[]on first call if it is currentlyNone.- Parameters:
annotation (Annotation) – The
Annotationto attach.- Return type:
None
- remove_annotation(index)[source]¶
Remove and return the annotation at index.
- Parameters:
index (int) – Zero-based position in the annotation list.
- Returns:
The removed
Annotation.- Raises:
IndexError – If the annotation list is
Noneor index is out of range.- Return type:
- to_json(file_path=None)[source]¶
Serialize this image’s metadata and annotations to JSON.
Pixel data is not included – only file path, dimensions, image type, and the full annotation list.
DicomImage¶
- class medical_image.data.dicom_image.DicomImage[source]¶
Bases:
ImageDICOM image backed by pydicom.
Supports lazy loading: the constructor stores the file path and validates the extension; pixel data is read only when
load()is called.- __init__(file_path=None, array=None, width=None, height=None, source_image=None)[source]¶
Initialise a DICOM image.
- Parameters:
- Raises:
ValueError – If file_path does not have a
.dcmextension.
- save()[source]¶
Write modified pixel data back to
{name}_modified.dcm.- Raises:
ValueError – If
dicom_datahas not been loaded.- Return type:
None
PNGImage¶
- class medical_image.data.png_image.PNGImage[source]¶
Bases:
ImagePNG image backed by Pillow.
Supports lazy loading: the constructor validates the file extension; pixel data is read only when
load()is called.- __init__(file_path)[source]¶
Initialise a PNG image.
- Parameters:
file_path (str) – Path to a
.pngfile.- Raises:
ValueError – If file_path does not have a
.pngextension.
InMemoryImage¶
- class medical_image.data.in_memory_image.InMemoryImage[source]¶
Bases:
ImageConcrete image that lives only in memory (no file I/O).
Both
load()andsave()are no-ops. Useful for intermediate processing results, temporary images, and test fixtures.
PatchGrid¶
- class medical_image.data.patch.PatchGrid[source]¶
Bases:
objectDivides an
Imageinto a regular grid of rectangular patches.Automatically pads the image with zeros when its dimensions are not evenly divisible by the requested patch size.
- classmethod from_image(image, patch_size)[source]¶
Create a PatchGrid from an
Image.Loads the image lazily if its
pixel_dataisNone.
- reconstruct()[source]¶
Reassemble the full image tensor from patches (removing padding).
Uses pre-allocated output tensor for O(1) allocations instead of O(rows * cols) concatenations.
- Returns:
The reconstructed
torch.Tensorwith the same layout as the original image.- Return type:
- to_image()[source]¶
Reconstruct the full image from patches and return a new Image.
Removes any padding that was added during splitting, clones the parent image, and replaces its pixel data with the reconstructed tensor. Follows the same pattern as
load().- Returns:
A new
Imagecontaining the reassembled pixel data.- Return type:
Patch¶
- class medical_image.data.patch.Patch[source]¶
Bases:
objectRepresents a patch extracted from an image.
- pixel_data¶
Tensor representing patch pixels.
- Type:
- to_image()[source]¶
Convert this patch into a new Image instance.
Clones the parent image and replaces its pixel data with the patch tensor. Follows the same pattern as
load().- Returns:
A new Image object containing only the patch pixels.
- Return type:
- load()[source]¶
Convert this patch into a new Image instance.
Deprecated since version Use:
to_image()instead for consistency with the ROI API.- Returns:
A new Image object containing only the patch pixels.
- Return type:
RegionOfInterest¶
- class medical_image.data.region_of_interest.RegionOfInterest[source]¶
Bases:
objectPyTorch-compatible Region of Interest (ROI) extractor.
Crops a sub-region from an
Imageusing one of three coordinate formats:Bounding Box:
[x_min, y_min, x_max, y_max]Polygon:
[(x1, y1), ..., (xn, yn)]Mask: 2D boolean NumPy array
- coordinates¶
ROI definition (format depends on annotation type).
- annotation_type¶
Detected ROI type.
- Type:
- classmethod from_center(image, cx, cy, half_size)[source]¶
Create a bounding-box ROI from center coordinates and half-size.
- Parameters:
- Returns:
RegionOfInterest with bounding box coordinates.
- Return type:
- load()[source]¶
Crop the image using the ROI definition and return a new Image.
Loads the source image lazily if it has not been loaded yet.
- Returns:
A cloned Image whose
pixel_datacontains only the cropped region.- Return type:
Annotation¶
- class medical_image.data.annotation.Annotation[source]¶
Bases:
objectA single annotation on a medical image.
Represents a geometric region (rectangle, ellipse, or polygon) with a label and optional metadata. The centroid is computed automatically in the constructor and exposed as
center.- shape¶
Geometry type of the annotation.
- Type:
- coordinates¶
Shape-specific coordinate data.
- __init__(shape, coordinates, label, metadata=None)[source]¶
Initialise an annotation and compute its center.
- Parameters:
shape (GeometryType) – Geometry type (
RECTANGLE,ELLIPSE, orPOLYGON).coordinates (List[int] | List[Tuple[int, int]]) – Coordinate data whose format depends on shape: - RECTANGLE:
[x_min, y_min, x_max, y_max]- ELLIPSE:[cx, cy, rx, ry]- POLYGON:[(x1, y1), (x2, y2), ...](>= 3 points)label (str) – Annotation label (e.g.
"mass","calcification").metadata (dict | None) – Optional extra info. Defaults to
{}.
- Raises:
ValueError – If coordinates do not match the shape contract.
- get_bounding_box()[source]¶
Return the axis-aligned bounding box enclosing the annotation.
- Returns:
[x_min, y_min, x_max, y_max]in pixel coordinates.- Raises:
ValueError – For unsupported geometry types.
- Return type:
- get_roi(padding=0, roi_type='bbox', image_shape=None)[source]¶
Return a region of interest around the annotation.
Computes the bounding box, applies padding, optionally clamps to image bounds, and returns the result in the requested shape.
- Parameters:
padding (int) – Extra pixels added on each side of the bounding box.
roi_type (str) – Output shape format.
"bbox"or"rectangle"returns{"type": ..., "coordinates": [x_min, y_min, x_max, y_max]}."ellipse"returns{"type": "ellipse", "coordinates": {"center": (cx, cy), "radii": (rx, ry)}}.image_shape (Tuple[int, int] | None) –
(height, width)used to clamp coordinates so the ROI stays within image bounds.Nonemeans no clamping.
- Returns:
dict with keys
"type"(str) and"coordinates".- Raises:
ValueError – If roi_type is not
"bbox","rectangle", or"ellipse".- Return type:
- to_dict()[source]¶
Serialize the annotation to a JSON-compatible dictionary.
The output includes computed fields (
center,bounding_box) so that consumers do not need to recompute them. Polygon coordinates are converted from tuples to nested lists for JSON compatibility.- Returns:
dict with keys
shape,coordinates,label,center,bounding_box, andmetadata.- Return type:
- classmethod from_dict(data)[source]¶
Deserialize an annotation from a dictionary.
Inverse of
to_dict(). Thecenterandbounding_boxfields in data are ignored (they are recomputed from coordinates).- Parameters:
data (dict) – Dictionary with at least
shape,coordinates, andlabelkeys.metadatais optional (defaults to{}).- Returns:
A new
Annotationinstance.- Return type:
GeometryType¶
- class medical_image.data.annotation.GeometryType[source]¶
Bases:
EnumSupported geometric shapes for annotations.
Each member defines the coordinate format expected by
Annotation:RECTANGLE–[x_min, y_min, x_max, y_max]ELLIPSE–[cx, cy, rx, ry](center + radii)POLYGON–[(x1, y1), (x2, y2), ...](>= 3 vertices)BOUNDING_BOX– backward-compatible alias forRECTANGLE
- RECTANGLE = 1¶
- ELLIPSE = 2¶
- POLYGON = 3¶
- BOUNDING_BOX = 1¶