Skip to main content

MONAI

AI Segmentation 📥 Download Script

MONAI segmentation tutorial script.

Performs MONAI segmentation on the first volume in the opened project, splits a multilabel result into individual masks, keeps the largest label, filters to the largest connected region, generates a 3D preview, converts it to a surface, and performs simple surface cleanup and export.

Complete Example​

# Import necessary modules
import ScriptingApi as api

# Instantiate the Application class
# The Application class serves as the primary entry point for interacting with
# the software. To begin using the API, create an instance of this class.
# Use the original class name `Application` or the pythonic alias `app` or `application`
# as the variable name to improve IntelliSense support. For details, refer to the documentation.
app = api.Application()

# Close any open project
app.close_project()

# Open a specific project
project_path = R'C:\Data\MyProject.vvcx'
app.open_project(project_path)

# Get the name of the first volume
volumes = app.get_all_volume_names()
if len(volumes) == 0:
raise RuntimeError("No volumes found in project.")
volume_name = volumes[0]
print("Using volume:", volume_name)

# Get AI segmentation instance
# Use the pythonic alias `ai_segmentation` as the variable name to improve IntelliSense support.
# Hover over the variable to view available methods and properties.
# If no tooltip appears, IntelliSense does not recognize the variable name.
# For details, refer to the documentation.
ai_segmentation = app.get_ai_segmentation()

# Set the AI segmentation model type
ai_segmentation.set_model_type(api.AiSegmentationModelType.Monai)

# Check installation status and install if necessary
installed = ai_segmentation.get_installation_status()
if not installed:
print('Installation required: The AI model is not installed.')
print('Please run the application as an administrator to install it.')
print('Attempting to install the AI model now.')
installed = ai_segmentation.install_model()
if not installed:
raise RuntimeError('An error occurred during the installation of the AI model. The log file has been saved for troubleshooting.')
else:
print('The AI model is installed and ready for use.')
else:
print('The AI model is installed and ready for use.')

# Configure MONAI parameters
monai_params: api.MonaiParams = ai_segmentation.get_default_monai_params()
monai_params.bundle_dir = 'C:/Users/XYZ/.monai/wholeBody_ct_segmentation'
monai_params.overlap = 0.8

# Some AI models may not support GPU execution. Use CPU to ensure compatibility,
# but prefer GPU when available for optimal performance.
monai_params.device = 'gpu'

# Run MONAI segmentation
mask_names = ai_segmentation.run_monai([volume_name], monai_params)
if len(mask_names) == 0:
raise RuntimeError("Segmentation returned no masks (operation cancelled or failed).")
print("Generated masks:", mask_names)

# Get the name of the currently active mask
active_mask = app.get_active_mask_name()
print("Active mask:", active_mask)

# Get the mask_operations object to perform operations on masks
mask_operations = app.get_mask_operations()

# Split multi-label mask into individual masks and extract only the largest label by volume
splitted_masks = mask_operations.split_multi_label_mask(volume_name, active_mask, True, 1)
if len(splitted_masks) == 0:
raise RuntimeError("Split operation did not produce separate labels.")
print("Splitted masks (largest label retained):", splitted_masks)

# Retain only the largest connected region
mask_operations.filter_regions(splitted_masks, True, 1, 8)

# Show only the splited mask, hide the original multi-label mask
app.set_masks_visible([active_mask], False)
app.set_masks_visible(mask_names, True)

# Set 3D preview quality and generate preview of all visible masks
app.set_mask_3d_preview_quality(api.Mask3dPreviewQuality.Optimal)
app.generate_mask_3d_preview(app.get_visible_mask_names())

# Convert generated 3D preview to surface objects
surfaces = mask_operations.convert_3d_preview_to_surface_objects()
if len(surfaces) == 0:
raise RuntimeError("No surface generated from 3D preview.")
print("Created surfaces:", surfaces)

# Get the name of the currently active surface
surface = app.get_active_surface_name()
print(surface)

# Get the surface_operations object to perform operations on surfaces
surface_operations = app.get_surface_operations()

# Filter surface to keep only the largest shell
surface_filter_shells_params = api.SurfaceFilterShellsParams()
surface_filter_shells_params.largest_shells = 1
surface_operations.filter_shells(surface, api.SurfaceFilterShellsMethod.LargestShells, surface_filter_shells_params)

# Remesh the surface for better quality
surface_operations.remesh([surface])

# Fix surface issues using diagnostics checks
surface_diagnostics_checks = api.SurfaceDiagnosticsChecks()
surface_operations.fix_surface(surface, surface_diagnostics_checks)

# Hide all volumes and masks to focus on the surface
app.set_volumes_visible(app.get_all_volume_names(), False)
app.set_masks_visible(app.get_all_mask_names(), False)

# Isolate the surface
app.isolate_surfaces([surface])

# Export the surface to disk in STL format
surface_operations.export_surface_to_disk(surface, 'C:/tmp/surface.stl')

# Set surface representation to Solid with Edges
surface_render_properties_operations = surface_operations.get_render_properties_operations()
surface_render_properties_operations.set_representation([surface], api.SurfaceRepresentation.SolidEdges)

print("MONAI tutorial completed successfully.")