mesh_to_mask#

medicalimageanalysis.utils.roi.to_mask.mesh_to_mask(poly, shape_zyx, origin, spacing, direction, ramp=None, direction_rows=True)[source]

Rasterize a closed mesh by cutting it at the CT slice centres.

The mask values come from the signed distance to the cut rings on each slice.

Parameters:
  • poly (vtk.vtkPolyData) – Closed surface mesh in world coordinates (a pv.PolyData works too).

  • shape_zyx (tuple[int, int, int]) – Output mask shape (nz, ny, nx).

  • 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.

  • ramp (float | None) – Width in mm of the 0..255 boundary ramp. None uses the default.

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

Returns:

uint8 mask (nz, ny, nx), 0..255, >= 128 inside.

Return type:

np.ndarray

Examples

Rasterize a sphere onto a 2 mm slice grid:

>>> import numpy as np
>>> import pyvista as pv
>>> from medicalimageanalysis.utils.roi.to_mask import mesh_to_mask
>>> sphere = pv.Sphere(radius=8.0, center=(16.0, 16.0, 16.0))
>>> mask = mesh_to_mask(sphere, (16, 32, 32), (0.0, 0.0, 0.0), (1.0, 1.0, 2.0), np.eye(3))
>>> bool(mask[8, 16, 16] >= 128)          # centre, z = 16 mm
True
>>> bool(mask[0, 16, 16] >= 128)          # z = 0 mm, outside
False

Rasterize a mesh onto a loaded image’s grid:

>>> from medicalimageanalysis import Data
>>> ct = Data.image['CT 01']
>>> mask = mesh_to_mask(mesh, ct.array.shape, ct.origin, ct.spacing, ct.matrix)