seg2mesh.config

This module contains configuration classes for constructing pipelines to process segmentations and generate surface meshes.

class seg2mesh.config.AcvdOptions(**data)

Bases: BaseModel

edge_length: float

Target edge length for ACVD remeshing

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class seg2mesh.config.MmgOptions(**data)

Bases: BaseModel

divisions_per_circle: float

Assuming a circle with the local radius of curvature, edge length is defined as arc length of circle with this many divisions

hgrad: float

Ratio defining how quickly edge length can change

hmax: float

Maximum target element edge length

hmin: float

Minimum target element edge length

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class seg2mesh.config.SegmentationPipeline(**data)

Bases: BaseModel

Configuration class for a segmentation pipeline.

lut: dict[str, int] | None

Dictionary mapping a label name to its integer value. If only 1 file is indicated for source_files, it is recommended to define this lut. Otherwise, label names will just be strings of their respective integer values.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

output_path: str | Path

Path to write output files to.

processing_options: SegmentationProcessing

BaseModel defining segmentation processing options.

source_files: list[str | Path]

List of label images.

target_voxel_size: tuple[float, float, float]

The target voxel size for the output mesh.

class seg2mesh.config.SegmentationProcessing(**data)

Bases: BaseModel

Configuration class for segmentation processing.

close: bool

Perform morphological closing on segmented labels

closing_radius: tuple[int, int, int]

The radius of the closing operation

contiguous_closing_radius: tuple[int, int, int]

The radius of the contiguous closing operation

make_contiguous: list[tuple[str, str]]

A list of tuples specifying the labels to make contiguous. First element in tuple will overwrite the second element.

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

open_list: list[str]

A list of label ‘Short Name’ to perform morphological opening on

opening_radius: tuple[int, int, int]

The radius of the opening operation

spur_removal_length: int

The length of spurs (in voxels) to remove

class seg2mesh.config.SurfaceMeshPipeline(**data)

Bases: BaseModel

calculate_classification_metrics: bool

Whether to calculate classification metrics: Dice Coefficient, Intersection over Union, and Accuracy

calculate_distance_metrics: bool

Whether to calculate Hausdorff, Mean Symmetric Surface, and Root Mean Square Distance metrics

label_file: str | Path

Path to image file containing all anatomical labels

lut_file: str | Path

Path to JSON file containing lookup table for anatomical labels

model_config: ClassVar[ConfigDict] = {'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

output_formats: list[Literal['vtp', 'stl', 'ply', 'obj']]
output_path: str | Path

Path for output files

remesh_options: MmgOptions | AcvdOptions | None

BaseModel for remesh options. If None, no remesh is performed.

taubin_iterations1: int

Number of iterations for the first Taubin smoothing operation. NOTE: If <= 0, no smoothing is performed.

taubin_iterations2: int

Number of iterations for the Taubin smoothing operation after remesh NOTE: If <= 0 or if remesh_options is None, no smoothing is performed.

taubin_smoothing_factor1: float

Passband for the first Taubin smoothing operation

taubin_smoothing_factor2: float

Passband for the Taubin smoothing operation after remesh

voxel_edge: float

Voxel edge length to use when voxelizing mesh for classification metric calculation.

seg2mesh.config.parse_model_from_json(model, file)
Return type:

TypeVar(BaseModelType)

seg2mesh.config.save_model_to_json(model, file)

seg2mesh.vol

class seg2mesh.vol.NamedLabelImage(lut, image)

Bases: object

image: Image
lut: dict[str, int]
class seg2mesh.vol.NamedVTKImage(lut, image)

Bases: object

image: vtkImageData
lut: dict[str, int]
seg2mesh.vol.convert_segmentation_to_vtk(segmentation)

Converts a NamedLabelImage to a NamedVTKImage.

Parameters:

segmentation (NamedLabelImage) – The NamedLabelImage image to convert.

Return type:

NamedVTKImage

Returns:

A NamedVTKImage with converted image data and same lookup table.

seg2mesh.vol.create_canvas_for_volumes(volumes, spacing)

Create a unified canvas image from a list of volumes and target spacing.

Parameters:
  • volumes (list[Image]) – List of SimpleITK Image objects to resample.

  • spacing (tuple[float, ...]) – The target spacing for the canvas.

Return type:

Image

Returns:

A SimpleITK Image representing the unified canvas.

seg2mesh.vol.create_lut_from_label_image(label_image)
Return type:

dict[str, int]

seg2mesh.vol.make_contiguous(label1, label2, closing_radius)

Adjust label1 and label2 to be contiguous. label1 takes precedence over label2

Parameters:
  • label1 (Image) – The first label image.

  • label2 (Image) – The second label image.

  • closing_radius (tuple[int, int, int]) – The radius (in voxels) for dilation and morphological closing operations.

Return type:

tuple[Image, Image]

Returns:

A tuple of the adjusted label1 and label2 images.

seg2mesh.vol.process_segmentation(segmentation, options)

Apply a processing workflow to the segmentation.

Parameters:
Return type:

NamedLabelImage

Returns:

The processed segmentation as a NamedLabelImage.

seg2mesh.vol.remove_islands(image)

Remove islands (by keeping only the largest connected component) in a binary image.

Parameters:

image (Image) – The binary image to process.

Return type:

Image

Returns:

The image with islands removed.

seg2mesh.vol.resample_greyscale(image, spacing=None)
Return type:

Image

seg2mesh.vol.resample_label_image(image, spacing, transform=<SimpleITK.SimpleITK.Transform; proxy of <Swig Object of type 'itk::simple::Transform *'> >)

Resamples a label image to the specified spacing and SimpleITK Transform (default is identity). The sitkLabelLinear interpolator is used to better preserve labels during resampling.

Parameters:
  • image (Image) – The input label image to resample.

  • spacing (tuple[float, float, float]) – The desired spacing for the output image.

  • transform (Transform) – The transform to apply during resampling.

Return type:

Image

Returns:

The resampled label image.

seg2mesh.vol.resample_volumes_to_canvas(volumes, canvas)

Resample image volumes to a unified canvas. create_canvas_for_volumes() can be used to create a suitable canvas.

Parameters:
  • volumes (list[Image]) – List of SimpleITK Image objects to resample.

  • canvas (Image) – The target canvas to resample to.

Return type:

NamedLabelImage

Returns:

A NamedLabelImage with the resampled volumes and LUT mapping label names to integer values.

seg2mesh.smesh

seg2mesh.smesh.add_scalardict_to_field_data(field_data, poly)
Return type:

vtkPolyData

seg2mesh.smesh.clean_poly(poly)

Clean the input vtkPolyData using vtkCleanPolyData and fill any holes using vtkFillHolesFilter.

Parameters:

poly (vtkPolyData) – The input vtkPolyData to be cleaned.

Return type:

vtkPolyData

Returns:

The cleaned vtkPolyData with holes filled.

seg2mesh.smesh.compute_normals(poly)

Compute vertex normals for the input vtkPolyData using vtkPolyDataNormals. Normal consistency and splitting at feature edges are enabled.

Parameters:

poly (vtkPolyData) – The input vtkPolyData to compute normals for.

Return type:

vtkPolyData

Returns:

The vtkPolyData with computed normals.

seg2mesh.smesh.constrained_laplacian_smooth(poly, constrain_poly, iterations=40, relaxation_factor=1.0)
Return type:

vtkPolyData

seg2mesh.smesh.evaluate_distance_metrics(poly1, poly2)

Calculates distance error metrics including Hausdorff distance, Mean Symmetric Surface Distance, and Root Mean Square Distance.

Parameters:
  • poly1 (vtkPolyData) – The current mesh to compare.

  • poly2 (vtkPolyData) – The reference mesh to compare against.

Return type:

tuple[vtkPolyData, dict[str, float]]

Returns:

A tuple containing PolyData with poly1 topology with shortest (point-cell calculated) distances from poly1 to poly2 stored on vertices and metrics stored as FieldData and a dictionary of metrics. NOTE: The vertex distances are only poly1 to poly2 distances, but metrics are calculated using both poly1 to poly2 and poly2 to poly1 distances.

seg2mesh.smesh.evaluate_polydata_distance(poly1, poly2)
seg2mesh.smesh.evaluate_volume_metrics(poly1, poly2, voxel_edge)

Calculate classification scores based on voxelized volumes.

Parameters:
  • poly1 (vtkPolyData) – The current mesh to compare.

  • poly2 (vtkPolyData) – The reference mesh to compare against.

  • voxel_edge (float) – The edge length of the voxels used for voxelization.

Return type:

dict[str, float]

Returns:

A dictionary of volume metrics including Dice Coefficient, Intersection over Union, and Accuracy.

seg2mesh.smesh.extract_isocontours(volume)

Triangulate isocontours from vtkImageData using vtkDiscreteFlyingEdges3D, extract using vtkThreshold, clean, and add to dictionary by name from the LUT.

Parameters:

volume (NamedVTKImage) – Contains vtkImage Data, image, and lookup table, lut, mapping image intensity values to contour names.

Return type:

dict[str, vtkPolyData]

Returns:

A dictionary of isocontours, where the keys are contour names and the values are vtkPolyData.

seg2mesh.smesh.get_compatible_origin_and_size(poly1, poly2, voxel_edge)

Given two vtkPolyData objects, returns the compatible origin and size to create corresponding voxelizations.

Parameters:
  • poly1 (vtkPolyData) – The first vtkPolyData object.

  • poly2 (vtkPolyData) – The second vtkPolyData object.

  • voxel_edge (float) – The edge length of the voxels.

Return type:

tuple[ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]], ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]]

Returns:

The compatible origin and size as a tuple of numpy arrays.

seg2mesh.smesh.get_curvatures(poly, curvature_type='maximum')

Calculate the curvatures of the given vtkPolyData.

Parameters:
  • poly (vtkPolyData) – The vtkPolyData to calculate curvatures for.

  • curvature_type (Literal['maximum', 'minimum', 'gaussian', 'mean']) – The type of curvature to calculate.

Return type:

vtkPolyData

Returns:

The vtkPolyData with curvature values added as point data.

seg2mesh.smesh.image_boolean(image1, image2, operation)
Return type:

vtkImageData

seg2mesh.smesh.mmg_remesh(poly, hmax=1.0, hmin=0.2, divisions_per_circle=8.0, hgrad=1.5)

Adaptive remeshing using mmg3d. Note: we override the default Hausdorff parameter and rely on metric values defined by local curvature to control element size.

Parameters:
  • poly (vtkPolyData) – The vtkPolyData to be remeshed.

  • hmax (float) – The maximum target element edge length.

  • hmin (float) – The minimum target element edge length.

  • divisions_per_circle (float) – Local target edge length defined as a function of radius of curvature. Number of divisions per circle of this radius.

  • hgrad (float) – Ratio defining how fast element edge length can change. Higher values mean faster changes.

Return type:

vtkPolyData

Returns:

The remeshed vtkPolyData.

seg2mesh.smesh.remesh(poly, edge_length=1.0)

Remesh the input vtkPolyData using ACVD (Approximated Centroidal Voronoi Diagrams).

Parameters:
  • poly (vtkPolyData) – The input vtkPolyData to be remeshed.

  • edge_length (float) – The target edge length for the remeshed mesh.

Return type:

vtkPolyData

Returns:

The remeshed vtkPolyData.

seg2mesh.smesh.remove_islands(poly)
Return type:

vtkPolyData

seg2mesh.smesh.repair_mesh(mesh)

Uses the pymeshfix library to clean and repair the input mesh

Return type:

vtkPolyData

Returns:

The repaired vtkPolyData.

seg2mesh.smesh.taubin_smooth(poly, iterations=40, smoothing_factor=0.8)

Apply Taubin smoothing to the input vtkPolyData.

Parameters:
  • poly (vtkPolyData) – The input vtkPolyData to be smoothed.

  • iterations (int) – The number of smoothing iterations. More iterations result in smoother output.

  • smoothing_factor (float) – The adjusts the passband parameter for the smoothing filter to mapping 0.0 to 1.0 to a passband of 0.0001 to 1.0. This is equivalent to the Slicer3D implementation.

Return type:

vtkPolyData

Returns:

The smoothed vtkPolyData.

seg2mesh.smesh.voxelize_mesh(mesh, voxel_edge, origin, size, max_voxels=1000000000)

Voxelizes a mesh into a vtkImageData volume using the vtkPolyDataToImageStencil filter.

Parameters:
  • voxel_edge (float) – The edge length of the voxels.

  • origin (ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]) – The origin of the vtkImageData volume.

  • size (ndarray[tuple[Any, ...], dtype[TypeVar(_ScalarT, bound= generic)]]) – The size ([x, y, z] in voxels) of the vtkImageData volume.

  • max_voxels (int) – The maximum number of voxels allowed, to avoid excessive memory usage.

Return type:

vtkImageData

Returns:

The vtkImageData volume.

seg2mesh.vol_pipeline

seg2mesh.vol_pipeline.main(config)

A pipeline for processing segmentation volumes. See Segmentation Label Volume Processing Pipeline.

Parameters:

config (SegmentationPipeline) – A SegmentationPipeline configuration either instantiated in-code or provided via a JSON filepath CLI argument.

seg2mesh.smesh_pipeline

seg2mesh.smesh_pipeline.main(config)