mask_to_contours#

medicalimageanalysis.utils.roi.to_contours.mask_to_contours(mask, origin, spacing, direction, level=None, as_list=False, direction_rows=True)[source]

Trace a mask into world-space contours with marching squares on each slice.

The mask is padded by one voxel so contours touching the image edge still close.

Parameters:
  • mask (np.ndarray) – Mask in z-y-x order, (nz, ny, nx). Either binary (0/1) or uint8 0..255 with >= 128 inside.

  • origin (tuple[float, float, float]) – World (x, y, z) of voxel (0, 0, 0).

  • spacing (tuple[float, float, float]) – Voxel spacing (sx, sy, sz) in mm.

  • direction (np.ndarray) – 3x3 image direction matrix.

  • level (float | None) – Iso-level to trace. If None, 127.5 for a uint8 0..255 mask (sub-pixel boundary) and 0.5 for a binary mask.

  • as_list (bool) – If True, return a flat list of rings instead of a dictionary.

  • direction_rows (bool) – Layout of direction, forwarded to normalize_direction.

Returns:

{slice_index: [(n, 3) world rings]} for every non-empty slice, or a flat list of rings when as_list=True.

Return type:

dict[int, list[np.ndarray]] | list[np.ndarray]

Examples

Trace a binary box mask (2 mm slices):

>>> import numpy as np
>>> from medicalimageanalysis.utils.roi.to_contours import mask_to_contours
>>> mask = np.zeros((8, 32, 32), dtype=np.uint8)
>>> mask[2:6, 8:24, 8:24] = 1
>>> contours = mask_to_contours(mask, (0.0, 0.0, 0.0), (1.0, 1.0, 2.0), np.eye(3))
>>> sorted(contours.keys())
[2, 3, 4, 5]
>>> float(contours[2][0][:, 2].mean())      # slice 2 -> z = 4 mm
4.0

Get a flat list of rings instead:

>>> rings = mask_to_contours(
...     mask, (0.0, 0.0, 0.0), (1.0, 1.0, 2.0), np.eye(3), as_list=True,
... )
>>> len(rings)
4

Trace a probability map at a custom level:

>>> probability = (np.random.rand(8, 32, 32) * 255).astype(np.uint8)
>>> contours = mask_to_contours(
...     probability, (0.0, 0.0, 0.0), (1.0, 1.0, 2.0), np.eye(3), level=200,
... )