ROI#

class medicalimageanalysis.structure.roi.Roi(image, position=None, name=None, color=None, visible=False, filepaths=None, plane=None)[source]#

Bases: object

Region of interest of one image: contours, surface mesh and slicing.

ROIs are normally made by the image (image.add_roi, image.create_roi, RTSTRUCT / MHD input) and stored in image.roi, which looks them up by permanent id or by name (image.roi[3], image.roi[‘Liver’]).

id#

Permanent ROI id, written by the image’s ROI registry. The same ROI has the same id on every image (see Data.new_roi_id). It never changes, so use it as the database key. None until the ROI is added to an image.

Type:

int | None

name#

User name, written by the image’s ROI registry. Change it with Data.rename_roi, never by assigning roi.name.

Type:

str | None

group_id#

ROI group the ROI is in (image.roi_group), the same on every image. None = ungrouped. Set it with Data.set_group(‘roi’, …).

Type:

int | None

contour_position#

World contours, (N, 3) in mm.

Type:

list[np.ndarray] | None

contour_pixel#

Pixel contours, (N + 1, 3) x-y-z indices, closing point repeated.

Type:

list[np.ndarray] | None

mesh#

Closed surface in mm. Setting it clears the slice cache.

Type:

pv.PolyData | None

volume, com, bounds

Mesh volume (mm^3), center and bounds, set when a mesh is built.

slice_cache_size#

Maximum number of cached slices per ROI, across all planes and views. Least recently used are dropped first.

Type:

int

Examples

Look up an ROI and read its geometry:

>>> import medicalimageanalysis as mia
>>> image = mia.Data.image['CT 01']
>>> roi = image.roi['Liver']
>>> roi.volume / 1000   # mL
>>> roi.com

Build an ROI directly from world contours:

>>> from medicalimageanalysis.structure.roi import Roi
>>> roi = Roi(image, position=contours, name='GTV', color=(255, 0, 0), plane='Axial')
>>> roi.create_mesh()
slice_cache_size = 2500#
property mesh#
compute_bounding_box(position=True)[source]#

Axis-aligned bounding box of the contours.

Parameters:

position (bool) – True uses the world contours (mm). False uses the pixel contours (x-y-z indices).

Returns:

(xmin, xmax, ymin, ymax, zmin, zmax).

Return type:

tuple

Examples

Extent in mm:

>>> import medicalimageanalysis as mia
>>> roi = mia.Data.image['CT 01'].roi['Liver']
>>> xmin, xmax, ymin, ymax, zmin, zmax = roi.compute_bounding_box()
>>> width_mm = xmax - xmin

First and last axial slice index the ROI is drawn on:

>>> *_, kmin, kmax = roi.compute_bounding_box(position=False)
>>> slices = range(int(round(kmin)), int(round(kmax)) + 1)
compute_components()[source]#

Split the mesh into connected components.

Returns:

One mesh per connected region, largest first. None if the ROI has no mesh.

Return type:

list[pv.UnstructuredGrid] | None

Examples

Count separate lesions in a GTV:

>>> import medicalimageanalysis as mia
>>> roi = mia.Data.image['CT 01'].roi['GTV']
>>> parts = roi.compute_components()
>>> n_lesions = len(parts)
>>> volumes_ml = [p.volume / 1000 for p in parts]
compute_contour(slice_location, offset=0)[source]#

Pixel contours drawn on one slice index of the ROI’s own plane.

Only contours whose slice index (z for ‘Axial’, y for ‘Coronal’, x for ‘Sagittal’) rounds to slice_location are returned. This reads the stored contours; use compute_mesh_slice for other planes or oblique views.

Parameters:
  • slice_location (int) – Slice index along the ROI’s plane normal.

  • offset (float) – Added to both in-plane coordinates, e.g. 0.5 to move from voxel centers to voxel corners.

Returns:

(N, 2) in-plane pixel loops, closed. Empty if nothing is drawn on that slice.

Return type:

list[np.ndarray]

Examples

Loops on axial slice 40:

>>> import medicalimageanalysis as mia
>>> roi = mia.Data.image['CT 01'].roi['Liver']
>>> loops = roi.compute_contour(40)
>>> loops[0].shape[1]
2

Shifted half a pixel for drawing on a pixel-corner grid:

>>> loops = roi.compute_contour(40, offset=0.5)

A slice outside the ROI:

>>> roi.compute_contour(-1)
[]
compute_mask()[source]#

Rasterize the world contours into a binary mask on the image grid.

Returns:

(z, y, x) mask with the same shape as image.dimensions.

Return type:

np.ndarray

Raises:

ValueError – If the rasterized mask does not match image.dimensions.

Examples

Mask and voxel volume:

>>> import numpy as np
>>> import medicalimageanalysis as mia
>>> image = mia.Data.image['CT 01']
>>> mask = image.roi['Liver'].compute_mask()
>>> mask.shape == tuple(image.dimensions)
True
>>> voxel_ml = mask.astype(bool).sum() * np.prod(image.spacing) / 1000

Mean HU inside the ROI:

>>> mean_hu = image.array[mask.astype(bool)].mean()
compute_mesh_slice(origin=None, plane=None, offset=0, rigid_matrix=None, return_pixel=False, grid=None, use_cache=True)[source]#

Slice the ROI mesh along a displayed plane.

The plane comes from grid (default: this image’s own view of plane at origin), so oblique views work the same as axis-aligned ones. A rigid_matrix places the mesh in another image’s world without moving it; the cutter’s spatial index is reused.

Results are cached in one LRU per ROI, keyed by the view geometry (axes, in-plane spacing), the rigid matrix, the slice origin (rounded to 1 um), offset and return_pixel. Scrolling back over a slice reuses the cached result. Rotating, flipping order or rigid dragging only creates new keys; old ones age out. Any mesh replacement clears the cache via the mesh setter.

The returned tuple/list is the cached object; copy it before modifying it in place.

Parameters:
  • origin (array-like (3,) | None) – World position of the plane’s top-left pixel, e.g. image.display.position[plane]. Used only when grid is None.

  • plane (str | None) – ‘Axial’, ‘Sagittal’ or ‘Coronal’. Used only when grid is None.

  • offset (float) – Added to both pixel coordinates when return_pixel=True.

  • rigid_matrix (np.ndarray (4, 4) | None) – Maps this image’s world to the displayed world, as returned by Rigid.get_display_matrix. Identity if None.

  • return_pixel (bool) – False returns the cut as world-space PolyData. True returns 2D (column, row) pixel loops on the grid.

  • grid (dict | None) – Plane in the displayed world, from display.get_grid(plane, origin). Pass the base image’s grid to draw this ROI on another image’s view.

  • use_cache (bool) – If True, read and store the result in the slice cache.

Returns:

(pv.PolyData, None) when return_pixel=False, or (list[np.ndarray], None) of (N, 2) loops when return_pixel=True. (None, None) / ([], []) if the ROI has no mesh.

Return type:

tuple

Examples

Pixel loops on the axial slice currently shown:

>>> import medicalimageanalysis as mia
>>> image = mia.Data.image['CT 01']
>>> roi = image.roi['Liver']
>>> loops, _ = roi.compute_mesh_slice(origin=image.display.position['Axial'], plane='Axial',
...                                   return_pixel=True)

The same cut in world coordinates:

>>> cut, _ = roi.compute_mesh_slice(origin=image.display.position['Axial'], plane='Axial')
>>> cut.bounds

An MR ROI drawn on the CT axial view through a rigid registration:

>>> mr = mia.Data.image['MR 01']
>>> rigid = mia.Data.rigid['CT 01_MR 01']
>>> grid = image.display.get_grid('Axial', image.display.position['Axial'])
>>> loops, _ = mr.roi['Liver'].compute_mesh_slice(
...     grid=grid,
...     rigid_matrix=rigid.get_display_matrix('CT 01', 'MR 01'),
...     return_pixel=True,
... )

Skip the cache for a one-off cut:

>>> cut, _ = roi.compute_mesh_slice(origin=image.display.position['Sagittal'], plane='Sagittal',
...                                 use_cache=False)
convert_pixel_to_position(pixel=None)[source]#

Convert x-y-z pixel contours to world contours.

Fractional indices are allowed. No closing point is added, so a round trip through convert_position_to_pixel keeps the repeated point.

Parameters:

pixel (list[np.ndarray]) – Pixel contours, (N, 3) x-y-z indices.

Returns:

World contours, (N, 3) in mm.

Return type:

list[np.ndarray]

Examples

The first voxel maps to the image origin:

>>> import numpy as np
>>> import medicalimageanalysis as mia
>>> image = mia.Data.image['CT 01']
>>> roi = image.roi['Liver']
>>> position = roi.convert_pixel_to_position([np.array([[0.0, 0.0, 0.0]])])
>>> np.allclose(position[0][0], image.origin)
True

Round trip of the ROI’s own contours:

>>> back = roi.convert_pixel_to_position(roi.contour_pixel)
>>> np.allclose(back[0][:-1], roi.contour_position[0])
True
convert_position_to_pixel(points, base=True, plane=None, origin=None)[source]#

Convert world contours to pixel coordinates.

With base=True the result is the image’s own x-y-z pixel index. With base=False it is the 2D (column, row) pixel of a displayed plane, using the current view rotation (image.display.matrix) and the plane’s top-left origin. Each returned loop is closed by repeating its first point.

Parameters:
  • points (list[np.ndarray]) – World contours, (N, 3) in mm.

  • base (bool) – True for image pixel indices, False for display pixels.

  • plane (str | None) – ‘Axial’, ‘Sagittal’ or ‘Coronal’. Required when base=False.

  • origin (array-like (3,) | None) – World position of the plane’s top-left pixel, e.g. image.display.position[plane]. Required when base=False.

Returns:

(N + 1, 3) x-y-z indices if base=True, else (N + 1, 2) (column, row).

Return type:

list[np.ndarray]

Examples

Image pixel indices; the loop gains a closing point:

>>> import numpy as np
>>> import medicalimageanalysis as mia
>>> image = mia.Data.image['CT 01']
>>> roi = image.roi['Liver']
>>> square = np.array([[-20, -20, 50], [20, -20, 50], [20, 20, 50], [-20, 20, 50]], dtype=float)
>>> pixel = roi.convert_position_to_pixel([square])
>>> pixel[0].shape
(5, 3)

Display pixels on the axial slice currently shown:

>>> xy = roi.convert_position_to_pixel([square], base=False, plane='Axial',
...                                    origin=image.display.position['Axial'])
>>> xy[0].shape
(5, 2)
create_cluster_mesh(points=None, set_mesh=False)[source]#

Remesh the current surface to near-uniform triangles (pyacvd).

Parameters:
  • points (int | None) – Target number of points. If None, it is chosen from the mesh volume and complexity.

  • set_mesh (bool) – If True, also replace self.mesh with the result.

Returns:

Clustered closed surface.

Return type:

pv.PolyData

Examples

Uniform 3000-point surface for registration or FE meshing:

>>> import medicalimageanalysis as mia
>>> roi = mia.Data.image['CT 01'].roi['Liver']
>>> mesh = roi.create_cluster_mesh(points=3000)

Automatic target, kept on the ROI:

>>> roi.create_cluster_mesh(set_mesh=True)
create_decimate_mesh(percent=None, set_mesh=False)[source]#

Decimate the current mesh.

Parameters:
  • percent (float | None) – Fraction of triangles to remove, 0 to 1. If None, it is chosen so that about 10 * sqrt(n_points) points remain.

  • set_mesh (bool) – If True, also replace self.mesh with the result.

Returns:

Decimated mesh.

Return type:

pv.PolyData

Examples

Preview a 90 % reduction without touching the ROI:

>>> import medicalimageanalysis as mia
>>> roi = mia.Data.image['CT 01'].roi['Liver']
>>> light = roi.create_decimate_mesh(percent=0.9)
>>> light.n_cells < roi.mesh.n_cells
True

Automatic target, kept on the ROI:

>>> mesh = roi.create_decimate_mesh(set_mesh=True)
>>> roi.mesh is mesh
True
create_discrete_mesh()[source]#

Build a voxel-stepped (un-smoothed) mesh from the pixel contours.

The surface follows the voxel faces, so its volume matches the voxel count of the mask. Sets mesh, volume, com and bounds.

Return type:

None

Examples

Compare the stepped volume with the smooth one:

>>> import medicalimageanalysis as mia
>>> roi = mia.Data.image['CT 01'].roi['Liver']
>>> roi.create_mesh()
>>> smooth_ml = roi.volume / 1000
>>> roi.create_discrete_mesh()
>>> discrete_ml = roi.volume / 1000
create_display_mesh(iterations=20, angle=60, passband=0.001)[source]#

Smooth the current mesh in place with a windowed sinc filter.

volume, com and bounds are not updated, so they still describe the mesh before smoothing.

Parameters:
  • iterations (int) – Number of smoothing passes.

  • angle (float) – Feature angle in degrees; edges sharper than this are kept.

  • passband (float) – Filter passband. Smaller values smooth more.

Return type:

None

Examples

Smooth a stepped mesh for 3D rendering:

>>> import medicalimageanalysis as mia
>>> roi = mia.Data.image['CT 01'].roi['Liver']
>>> roi.create_discrete_mesh()
>>> roi.create_display_mesh(iterations=30, passband=0.0005)
create_mesh(reduction=0, interpolate=False)[source]#

Build a smooth closed surface mesh from the world contours.

Sets mesh, volume, com and bounds (left unchanged if no mesh could be built).

Parameters:
  • reduction (float) – Decimation fraction applied once at the end, 0 to 1. 0 keeps every triangle; 0.5 removes about half.

  • interpolate (bool) – How far apart contour planes can be and still be joined. False (default): only contours on adjacent image slices are joined, using the slice spacing from spacing and direction. A missing slice leaves a gap, and each side is capped half a slice past its last contour. origin, spacing and direction must describe the grid the contours were drawn on (for RTSTRUCT, the referenced image). True: the slice spacing is the median spacing between contoured slices, so missing slices are filled by shape interpolation. Use this for deliberately sparse contours, contours drawn on a different grid, or sagittal / coronal contours. Gaps larger than 1.5x that spacing are still left open.

Return type:

None

Examples

Full-resolution mesh:

>>> import medicalimageanalysis as mia
>>> roi = mia.Data.image['CT 01'].roi['Liver']
>>> roi.create_mesh()
>>> full = roi.mesh.n_cells

Lighter mesh for display or registration:

>>> roi.create_mesh(reduction=0.5)
>>> roi.mesh.n_cells < full
True
create_sitk_mask()[source]#

Rasterize the contours into a SimpleITK image on the image grid.

Origin, spacing and direction are copied from the parent image, so the mask can be written or resampled with SimpleITK directly.

Returns:

Binary mask with the image geometry.

Return type:

SimpleITK.Image

Examples

Save the ROI as a NIfTI label:

>>> import SimpleITK as sitk
>>> import medicalimageanalysis as mia
>>> roi = mia.Data.image['CT 01'].roi['Liver']
>>> sitk_mask = roi.create_sitk_mask()
>>> sitk.WriteImage(sitk_mask, 'C:/Data/liver.nii.gz')

Geometry matches the image:

>>> sitk_mask.GetSize() == tuple(int(d) for d in roi.image.dimensions[::-1])
True
add_mesh(mesh)[source]#

Attach an existing mesh and read its volume, center and bounds.

Unlike update_mesh, the contours are kept.

Parameters:

mesh (pv.PolyData) – Closed surface in mm, in this image’s world.

Return type:

None

Examples

Attach a mesh loaded from disk:

>>> import pyvista as pv
>>> import medicalimageanalysis as mia
>>> roi = mia.Data.image['CT 01'].roi['Liver']
>>> roi.add_mesh(pv.read('C:/Data/liver.stl'))
>>> roi.volume / 1000   # mL
clear()[source]#

Remove the contours, mesh and derived geometry.

Name, color, visibility, file paths and group are kept.

Return type:

None

Examples

>>> import medicalimageanalysis as mia
>>> roi = mia.Data.image['CT 01'].roi['Liver']
>>> roi.clear()
>>> roi.contour_position is None, roi.mesh is None, roi.volume is None
(True, True, True)
clear_slice_cache()[source]#

Drop cached mesh slices.

Only needed if the mesh is edited in place (mesh.points = …, transform with inplace=True); replacing the mesh through the setter or update_mesh clears it automatically.

Return type:

None

Examples

Shift the mesh 2 mm in place, then clear the stale slices:

>>> import medicalimageanalysis as mia
>>> roi = mia.Data.image['CT 01'].roi['Liver']
>>> roi.mesh.points += [0.0, 0.0, 2.0]
>>> roi.clear_slice_cache()
convert_mask(mask)[source]#

Replace the ROI with the contours and mesh of a binary mask.

The mask is contoured slice by slice on self.plane, then the mesh is rebuilt. An empty mask clears the mesh.

Parameters:

mask (np.ndarray) – (z, y, x) binary mask on this image’s grid.

Return type:

None

Examples

Load an nnU-Net prediction into an ROI:

>>> import numpy as np
>>> import SimpleITK as sitk
>>> import medicalimageanalysis as mia
>>> image = mia.Data.image['CT 01']
>>> image.create_roi('Liver Pred', color=[0, 255, 0])
>>> label = sitk.GetArrayFromImage(sitk.ReadImage('C:/Data/pred.nii.gz'))
>>> image.roi['Liver Pred'].convert_mask((label == 1).astype(np.uint8))

Threshold the CT for bone:

>>> image.create_roi('Bone')
>>> image.roi['Bone'].convert_mask((image.array > 300).astype(np.uint8))
update_mesh(mesh)[source]#

Replace the ROI with an external mesh and drop the contours.

Use this when the mesh is now the source of truth (deformed, registered or edited in 3D). For a mesh that should sit alongside the existing contours, use add_mesh.

Parameters:

mesh (pv.PolyData) – Closed surface in mm, in this image’s world.

Return type:

None

Examples

Replace the liver with a deformed surface:

>>> import pyvista as pv
>>> import medicalimageanalysis as mia
>>> roi = mia.Data.image['CT 01'].roi['Liver']
>>> roi.update_mesh(pv.read('C:/Data/liver_deformed.vtk'))
>>> roi.contour_position is None
True
update_pixel(pixel, plane='Axial')[source]#

Replace the contours with new pixel contours and rebuild the mesh.

World contours are computed from pixel. None or an empty list clears the contours and mesh.

Parameters:
  • pixel (list[np.ndarray] | None) – Pixel contours, (N, 3) x-y-z indices.

  • plane (str) – Plane the contours were drawn on: ‘Axial’, ‘Coronal’ or ‘Sagittal’.

Return type:

None

Examples

A 20 x 20 pixel square on axial slices 40-42:

>>> import numpy as np
>>> import medicalimageanalysis as mia
>>> roi = mia.Data.image['CT 01'].roi['GTV']
>>> square = np.array([[200, 200], [220, 200], [220, 220], [200, 220]], dtype=float)
>>> pixel = [np.c_[square, np.full(4, k)] for k in (40, 41, 42)]
>>> roi.update_pixel(pixel, plane='Axial')
>>> roi.mesh is not None
True

Clear the ROI:

>>> roi.update_pixel(None)
>>> roi.mesh is None
True
update_position(position, plane='Axial')[source]#

Replace the contours with new world contours and rebuild the mesh.

Pixel contours are computed from position. None or an empty list clears the contours and mesh.

Parameters:
  • position (list[np.ndarray] | None) – World contours, (N, 3) in mm.

  • plane (str) – Plane the contours were drawn on: ‘Axial’, ‘Coronal’ or ‘Sagittal’.

Return type:

None

Examples

A 40 mm circle on three axial slices:

>>> import numpy as np
>>> import medicalimageanalysis as mia
>>> image = mia.Data.image['CT 01']
>>> roi = image.roi['GTV']
>>> t = np.linspace(0, 2 * np.pi, 64, endpoint=False)
>>> z0 = image.origin[2] + 40 * image.spacing[2]
>>> circles = [np.c_[20 * np.cos(t), 20 * np.sin(t), np.full(64, z0 + k * image.spacing[2])]
...            for k in range(3)]
>>> roi.update_position(circles, plane='Axial')
>>> len(roi.contour_pixel)
3

Copy contours from another ROI:

>>> roi.update_position(image.roi['Liver'].contour_position, plane=image.roi['Liver'].plane)