Skip to content

Instantly share code, notes, and snippets.

View lassoan's full-sized avatar

Andras Lasso lassoan

View GitHub Profile
@lassoan
lassoan / FillHolesInSegments.py
Last active February 4, 2024 18:54
Fills all internal holes inside segments. For example, fills in empty regions inside vertebral bodies segmented with Grow from seeds with intensity-based masking.
segmentationNode = slicer.mrmlScene.GetFirstNodeByClass('vtkMRMLSegmentationNode')
# set value to the size of the larges cracks in the segment surfaces
maximumHoleSizeMm = 2.0
############
masterVolumeNode = segmentationNode.GetNodeReference(segmentationNode.GetReferenceImageGeometryReferenceRole())
# Create segment editor to get access to effects
segmentEditorWidget = slicer.qMRMLSegmentEditorWidget()
# To show segment editor widget (useful for debugging):
@lassoan
lassoan / BoneAxis.py
Last active October 31, 2023 17:40
Compute bone axis in 3D Slicer by specifying two circles.
# Create a markups fiducial node and place 6 points then copy paste this code into 3D Slicer's Python console.
# Two circles will be created (one for each 3 points) and the axis will be computed by connecting their centers.
# The circles and the axis is updated as the fiducial point positions are adjusted.
def sphereFrom3Points(markupsNode, startPointIndex):
"""Compute center and radius of 3-point sphere from 3 fiducial points
source: https://stackoverflow.com/questions/20314306/find-arc-circle-equation-given-three-points-in-space-3d
"""
import numpy as np
A = np.zeros(3)
@lassoan
lassoan / CardiacAgatstonScoring
Last active September 18, 2023 03:36
Cardiac Agatston scoring function for 3D Slicer
# There are several variants of the metric. If you need to compute the metric slice by slice then
# you can use Mask volume effect to create a volume where all voxels are blanked out (set to -1000)
# except the calcifications in the selected vessel and compute the total score using this script.
# (based on Agatston (1990) - https://www.sciencedirect.com/science/article/pii/073510979090282T)
#
# Sample data set is available at:
# https://github.com/lassoan/PublicTestingData/releases/download/data/CardiacAgatstonScore.mrb
def computeAgatstonScore(volumeNode, minimumIntensityThreshold=130, minimumIslandSizeInMm2=1.0, verbose=False):
import numpy as np
@lassoan
lassoan / volumeAugment.py
Last active August 31, 2023 10:25
Training data augmentation with random volume translation, rotation, and deformation
# This script randomly warps a 3D volume and adds random translations, rotations,
# and save each resulting 3D volume (and a screenshot for quick overview)
#
# The script can be executed by copy-pasting into 3D Slicer's Python console
# or in a Jupyter notebook running 3D Slicer kernel (provided by SlicerJupyter extension).
#
# Prerequisites:
# - Recent Slicer-4.11 version
# - SlicerIGT extension installed (for random deformations)
@lassoan
lassoan / CurvedPlanarReformatting.py
Created October 22, 2019 13:05
Computing a panoramic X-ray from a cone-beam dental CT. Demonstration of how an image can be resampled along a curve - the code is not optimized for performance or quality and distance along curve is not scaled (we simply used all point indices instead of retrieving point indices based on desired distance along curve).
# Get a dental CT scan
import SampleData
volumeNode = SampleData.SampleDataLogic().downloadDentalSurgery()[1]
# Define curve
curveNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLMarkupsCurveNode')
curveNode.CreateDefaultDisplayNodes()
curveNode.GetCurveGenerator().SetNumberOfPointsPerInterpolatingSegment(25) # add more curve points between control points than the default 10
curveNode.AddControlPoint(vtk.vtkVector3d(-45.85526315789473, -104.59210526315789, 74.67105263157896))
curveNode.AddControlPoint(vtk.vtkVector3d(-50.9078947368421, -90.06578947368418, 66.4605263157895))
@lassoan
lassoan / SegmentGrowCutSimple.py
Last active May 6, 2023 15:08
This example demonstrates how to run Grow from seeds effect in batch mode (without GUI, using qMRMLSegmentEditorWidget) using 3D Slicer
# Generate input data
################################################
import SampleData
# Load master volume
sampleDataLogic = SampleData.SampleDataLogic()
masterVolumeNode = sampleDataLogic.downloadMRBrainTumor1()
# Create segmentation
@lassoan
lassoan / LoadRemoteFile.py
Last active February 13, 2023 17:07
Launch 3D Slicer from web browser to view 3D image file
The example was moved to Sandbox extension so that users can more easily install it:
https://github.com/PerkLab/SlicerSandbox/blob/master/LoadRemoteFile/LoadRemoteFile.py
More information: https://github.com/PerkLab/SlicerSandbox/blob/master/README.md#loadremotefile
@lassoan
lassoan / coloredvolumerendering.py
Last active December 11, 2022 22:39
Colored volume rendering
# This script can be used with this example scene:
# https://github.com/lassoan/PublicTestingData/releases/download/data/ColoredVolumeRenderingScene.mrb
volumeNode = getNode('Panoramix-cropped')
segmentationNode = getNode('Panoramix-cropped segmentation')
boostSegmentOpacity = False # Increase voxel value inside segments to allow making them them more opaque
volumesLogic = slicer.modules.volumes.logic()
segmentIds = vtk.vtkStringArray()
# Convert volume nodes of 3D Slicer to/from xarray and read/write into zarr format
def xarrayFromVolume(volumeNode) -> "xr.DataArray":
"""Convert an volume node to an xarray.DataArray.
Origin and spacing metadata is preserved in the xarray's coords. The
Direction is set in the `direction` attribute.
Dims are labeled as `x`, `y`, `z`, `t`, and `c`.
This interface is and behavior is experimental and is subject to possible
future changes."""
import xarray as xr
@lassoan
lassoan / LineProfile.py
Last active August 25, 2022 02:45
3D Slicer module for computing intensity profile in a volume along a ruler line
#
#
#
#
#
# This example has been completely reworked and converted to a module, now available at:
#
#
# https://github.com/lassoan/SlicerLineProfile/blob/master/LineProfile/LineProfile.py
#