MaskToContour#
- class medicalimageanalysis.utils.roi.discrete_converters.MaskToContour(mask=None, spacing=None, origin=None, matrix=None, plane='axial')[source]
Bases:
objectTrace a binary mask into slice-wise contours, in pixel and world coordinates.
Only outer contours are kept (no holes), simplified to their corner points.
- Parameters:
mask (np.ndarray | None) – Mask in z-y-x order. Any value > 0 counts as inside.
spacing (tuple[float, float, float] | None) – Voxel spacing in mm (x-y-z).
origin (tuple[float, float, float] | None) – World (x, y, z) of voxel (0, 0, 0).
matrix (np.ndarray | None) – 3x3 direction matrix.
plane (str) – ‘axial’, ‘coronal’ or ‘sagittal’ (case-insensitive).
Examples
>>> import numpy as np >>> from medicalimageanalysis.utils.roi.converters import MaskToContour >>> mask = np.zeros((8, 16, 16), dtype=np.uint8) >>> mask[2:6, 4:12, 4:12] = 1 >>> helper = MaskToContour(mask=mask, spacing=(1, 1, 2), origin=(0, 0, 0), matrix=np.eye(3)) >>> pixel, position = helper.create_contours() >>> len(pixel) # one contour per slice 4
- create_contours()[source]
Trace pixel contours, then convert them to world contours.
- Returns:
(contour_pixel, contour_position): (n, 3) voxel-index arrays and the matching (n, 3) world arrays in mm.
- Return type:
Examples
>>> import numpy as np >>> mask = np.zeros((8, 16, 16), dtype=np.uint8) >>> mask[2:6, 4:12, 4:12] = 1 >>> helper = MaskToContour(mask=mask, spacing=(1, 1, 2), origin=(0, 0, 0), matrix=np.eye(3)) >>> pixel, position = helper.create_contours() >>> pixel[0][:, 2] # slice index array([2, 2, 2, 2], dtype=int32) >>> position[0][:, 2] # world z in mm array([4., 4., 4., 4.])
- compute_pixel()[source]
Extract outer contours from each non-empty slice into contour_pixel.
- Return type:
None
Examples
Axial (default):
>>> import numpy as np >>> mask = np.zeros((8, 16, 16), dtype=np.uint8) >>> mask[2:6, 4:12, 4:12] = 1 >>> helper = MaskToContour(mask=mask) >>> helper.compute_pixel() >>> len(helper.contour_pixel) 4
Coronal (one contour per y slice):
>>> helper = MaskToContour(mask=mask, plane='coronal') >>> helper.compute_pixel() >>> len(helper.contour_pixel) 8
- compute_position()[source]
Convert contour_pixel to world coordinates in contour_position.
- Return type:
None
Examples
>>> import numpy as np >>> mask = np.zeros((8, 16, 16), dtype=np.uint8) >>> mask[2:6, 4:12, 4:12] = 1 >>> helper = MaskToContour( ... mask=mask, spacing=(0.5, 0.5, 2), origin=(-100, -100, 50), matrix=np.eye(3), ... ) >>> helper.compute_pixel() >>> helper.compute_position() >>> helper.contour_position[0][0] # pixel (4, 4, 2) array([-98., -98., 54.])