Skip to content

Instantly share code, notes, and snippets.

@lassoan
lassoan / save_volume_rendering.py
Created July 6, 2024 05:33
Write 3D Slicer image and segmentation renderings to image and video files
"""
Render image, segmentation, and colorized image slices and 3D.
How to call this from command line:
/home/jakob/dev/Slicer-5.7.0-linux-amd64/Slicer --python-script save_volume_rendering.py /path/to/output/folder mytest /path_to/ct_15mm.nii.gz /path/to/segmentation.nii.gz
"""
def captureSliceSweep(outputFilename, numberOfImages=25, lightboxColumns=5):
@lassoan
lassoan / SlicerImportURDF.py
Created June 21, 2024 18:10
URDF importer for 3D Slicer
# URDF importer for Slicer
#
# This script imports a universal robot description file (URDF) into 3D Slicer scene.
# This model can then be animated by updating the joint transforms by interactively modifying the transforms in 3D views
# or remotely via OpenIGTLink.
#
# Usage: Copy-paste this script into the Python console in 3D Slicer. The script automatically downloads an example URDF from github.
# You can use your own URDF file by setting `rootPath` and `urdfFilePath` to the path of your URDF file.
# Get URDF file.
@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 / 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 / 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 / FillHolesInSegments.py
Last active September 24, 2024 21:21
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 / 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)
# This gist contained a script that automatically removes table from a CT volume.
# The code was improved and turned into a Slicer module, available in the Sandbox extension:
# https://github.com/PerkLab/SlicerSandbox#remove-ct-table
#
# Source code:
# https://github.com/PerkLab/SlicerSandbox/blob/master/RemoveCtTable/RemoveCtTable.py#L251
@lassoan
lassoan / create-partof-hierarchy.py
Created March 30, 2020 22:12
Create 3D Slicer subject hierarchy from BodyParts3D
# Source data can be obtained from http://lifesciencedb.jp/bp3d/ (tested with partof_BP3D_4.0_obj_99)
# These input file must be loaded into the scene:
# - partof_inclusion_relation_list.txt and partof_element_parts.txt (loaded as Table nodes)
# - OBJ files
shNode = slicer.mrmlScene.GetSubjectHierarchyNode()
sceneItemID = shNode.GetSceneItemID()
def getItemParentsFmaIds(shNode, itemShItemId):
existingParentShItemId = shNode.GetItemParent(itemShItemId)