### Setup Python Environment for TotalSegmentator Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt This section details the manual setup of a Python virtual environment for the TotalSegmentator Horos plugin. It includes steps for creating the environment, activating it, and installing required packages like TotalSegmentator and rt_utils. It also shows how to test the installation. ```bash python3 -m venv ~/Library/Application\ Support/TotalSegmentatorHorosPlugin/PythonEnvironment source ~/Library/Application\ Support/TotalSegmentatorHorosPlugin/PythonEnvironment/bin/activate pip install --upgrade pip pip install TotalSegmentator==2.11.0 pip install rt_utils # required for DICOM RT-Struct import # Test installation python -c "from totalsegmentator.python_api import totalsegmentator; print('OK')" TotalSegmentator --version ``` -------------------------------- ### Horos Plugin Installation Guide Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt This section provides instructions for installing the TotalSegmentator Horos plugin. It covers building the plugin from source using Xcode and copying the built plugin to the Horos plugins directory. It also includes steps for code signing, which is necessary for Horos to load the plugin, and an alternative method for installing a prebuilt release. ```bash # Build plugin from source with Xcode cd TotalSegmentator-Horos-Plugin xcodebuild \ -project MyOsiriXPluginFolder-Swift/TotalSegmentatorHorosPlugin.xcodeproj \ -configuration Release \ -target TotalSegmentatorHorosPlugin \ build # Install to Horos plugins directory PLUGIN_SRC="MyOsiriXPluginFolder-Swift/build/Release/TotalSegmentatorHorosPlugin.osirixplugin" PLUGIN_DST="$HOME/Library/Application Support/Horos/Plugins/" rm -rf "$PLUGIN_DST/TotalSegmentatorHorosPlugin.osirixplugin" cp -R "$PLUGIN_SRC" "$PLUGIN_DST" # Code sign plugin (required for Horos to load) codesign --force --deep --sign - "$PLUGIN_DST/TotalSegmentatorHorosPlugin.osirixplugin" # Or install prebuilt release cp Releases/TotalSegmentatorHorosPlugin.osirixplugin \ "$HOME/Library/Application Support/Horos/Plugins/" codesign --force --deep --sign - \ "$HOME/Library/Application Support/Horos/Plugins/TotalSegmentatorHorosPlugin.osirixplugin" # Launch Horos - plugin appears in Plugins menu # First run auto-provisions Python environment at: # ~/Library/Application Support/TotalSegmentatorHorosPlugin/PythonEnvironment/ ``` -------------------------------- ### Systemd Service Control (Start/Stop Once) Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md These systemd commands are used to start, stop, or restart a service once. They do not configure the service for automatic startup on boot. ```bash systemctl start/stop/restart totalsegmentator_server ``` -------------------------------- ### Enabling Docker Service for Automatic Startup Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md This command enables the Docker service to start automatically on system boot. This is crucial for ensuring the Docker daemon is running after a server reboot, allowing containers with '--restart always' to function correctly. ```bash systemctl enable docker.service ``` -------------------------------- ### Systemd Service Management (Enable/Disable) Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md These systemd commands enable or disable a service to start automatically on system boot. Enabling ensures the service starts after a reboot, while disabling prevents it. ```bash systemctl enable/disable totalsegmentator_server ``` -------------------------------- ### Install Python Dependency (Bash) Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/README.md This command demonstrates how to install a specific Python dependency, 'rt_utils', within the plugin's isolated virtual environment. This is a troubleshooting step for cases where the dependency might be missing. ```bash ~/Library/.../PythonEnvironment/bin/pip install rt_utils ``` -------------------------------- ### Listing Running Docker Containers Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md This command displays a list of all currently running Docker containers. It's useful for monitoring the status of your deployed services. ```bash docker container ls ``` -------------------------------- ### Restarting a Docker Container Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md This command restarts a specified Docker container. It is useful for applying changes or recovering from a temporary issue without fully stopping and starting the service manually. ```bash docker restart totalsegmentator-server-job ``` -------------------------------- ### Configure GPU Devices for Inference Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt This section covers how to specify GPU devices for TotalSegmentator inference. It includes command-line examples for selecting specific GPUs (e.g., gpu:0, gpu:1) and a Python API example for using a GPU device. It also shows how to check CUDA availability and GPU details using PyTorch, and how to leverage Apple Silicon MPS acceleration. ```bash # Use specific GPU device TotalSegmentator -i scan.nii.gz -o output/ --device gpu:0 # Use second GPU TotalSegmentator -i scan.nii.gz -o output/ --device gpu:1 ``` ```python # Python API with GPU selection from totalsegmentator.python_api import totalsegmentator totalsegmentator( input="scan.nii.gz", output="output/", device="gpu:2", # use GPU device 2 task="total" ) # Check available devices import torch print(f"CUDA available: {torch.cuda.is_available()}") print(f"GPU count: {torch.cuda.device_count()}") for i in range(torch.cuda.device_count()): print(f"GPU {i}: {torch.cuda.get_device_name(i)}") # Apple Silicon MPS acceleration totalsegmentator( input="scan.nii.gz", output="output/", device="mps", # Metal Performance Shaders (macOS) task="total" ) ``` -------------------------------- ### Backing Up Server Data to Local Drive Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md This command uses rsync to perform a backup of server data to a local hard drive. It synchronizes files efficiently, transferring only the differences. Replace placeholders with actual username and server URL. ```bash rsync -avz @:/mnt/data/server-store /mnt/jay_hdd/backup ``` -------------------------------- ### Viewing Docker Container Logs Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md This command displays the standard output logs for a specified Docker container. It is essential for debugging issues with running containers. ```bash docker logs totalsegmentator-server-job ``` -------------------------------- ### Install Plugin into Horos (Bash) Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/README.md This script installs the compiled TotalSegmentator Horos Plugin into the Horos plugins directory. It removes any existing version, copies the new build, and then code-signs the plugin bundle, which is essential for macOS Gatekeeper. ```bash PLUGIN_SRC="MyOsiriXPluginFolder-Swift/build/Release/TotalSegmentatorHorosPlugin.osirixplugin" PLUGIN_DST="$HOME/Library/Application Support/Horos/Plugins/" rm -rf "$PLUGIN_DST/TotalSegmentatorHorosPlugin.osirixplugin" cp -R "$PLUGIN_SRC" "$PLUGIN_DST" codesign --force --deep --sign - "$PLUGIN_DST/TotalSegmentatorHorosPlugin.osirixplugin" ``` -------------------------------- ### Terraform Initialization, Validation, and Deployment Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md These Terraform commands are used to initialize the backend, validate the configuration, and apply infrastructure changes. Ensure you are in the 'resources' directory before running these commands. 'terraform apply -auto-approve' deploys resources without interactive confirmation. ```bash cd resources terraform init terraform validate terraform apply -auto-approve ``` -------------------------------- ### Python Environment Management for Plugin Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt This snippet illustrates the structure of the isolated Python environment provisioned by the plugin. The environment, typically located in `~/Library/Application Support/TotalSegmentatorHorosPlugin/`, contains the virtual environment binaries (`python`, `pip`), Python libraries, a directory for DICOM exports, and a log directory. This setup ensures that the plugin has its own dependencies without interfering with the system's Python installation. ```python # Plugin Swift code provisions environment (excerpt from Plugin.swift logic) # Environment structure: # ~/Library/Application Support/TotalSegmentatorHorosPlugin/ # ├── PythonEnvironment/ # virtualenv # │ ├── bin/python # │ ├── bin/pip # │ └── lib/python3.x/ # ├── temp_exports/ # DICOM export workspace # └── logs/ # execution logs ``` -------------------------------- ### Clone Repository and Build Plugin (Bash) Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/README.md This snippet shows how to clone the TotalSegmentator Horos Plugin repository and build the plugin using Xcode command-line tools. It ensures all necessary files are downloaded and compiled for installation. ```bash git clone https://github.com/ThalesMMS/TotalSegmentator-Horos-Plugin.git cd TotalSegmentator-Horos-Plugin ``` -------------------------------- ### Build Plugin with Xcode (Bash) Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/README.md This bash command utilizes `xcodebuild` to compile the TotalSegmentator Horos Plugin project in Release mode. It targets the main plugin executable, preparing it for installation. ```bash xcodebuild \ -project MyOsiriXPluginFolder-Swift/TotalSegmentatorHorosPlugin.xcodeproj \ -configuration Release \ -target TotalSegmentatorHorosPlugin \ build ``` -------------------------------- ### Local Testing of TotalSegmentator Flask Server Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md This command runs the TotalSegmentator Flask server locally for testing. It maps a local port, enables GPU usage, and mounts a volume for persistent storage. This is useful for testing the server's API endpoints. ```bash docker run -p 80:5000 --gpus 'device=0' --ipc=host -v /home/jakob/dev/TotalSegmentator/store:/app/store totalsegmentator:master /app/run_server.sh ``` -------------------------------- ### Stopping and Removing Exited Docker Containers Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md These commands stop a specific Docker container and then remove all containers that have exited. This helps in cleaning up stopped containers and freeing up resources. ```bash docker stop totalsegmentator-server-job docker rm $(docker ps -a -q -f status=exited) ``` -------------------------------- ### Python API: Liver Segmentation Example Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt Example of using the TotalSegmentator Python API for liver segmentation in oncology. It segments liver segments from a CT scan using the 'liver_segments' task. ```python from totalsegmentator.python_api import totalsegmentator totalsegmentator("liver_ct.nii.gz", "liver_out/", task="liver_segments") ``` -------------------------------- ### Removing All Exited Docker Containers Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md This command removes all Docker containers that have exited. This is a more general cleanup command compared to the one that also stops a specific container. ```bash docker rm $(docker ps -a -q -f status=exited) ``` -------------------------------- ### Python API: Brain Segmentation Example Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt Example of using the TotalSegmentator Python API to perform brain structure segmentation. It takes an input image file, an output directory, and specifies the 'brain_structures' task. ```python from totalsegmentator.python_api import totalsegmentator totalsegmentator("brain_mri.nii.gz", "brain_out/", task="brain_structures") ``` -------------------------------- ### Python API: Cardiac Segmentation Example Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt Example of using the TotalSegmentator Python API for cardiac imaging segmentation. It processes a cardiac CT scan and segments heart chambers using the 'heartchambers_highres' task. ```python from totalsegmentator.python_api import totalsegmentator totalsegmentator("cardiac_ct.nii.gz", "cardiac_out/", task="heartchambers_highres") ``` -------------------------------- ### Local Testing of TotalSegmentator Docker Container Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md This command runs the TotalSegmentator Docker container locally for testing purposes. It mounts a local directory for input and output and utilizes GPU acceleration. The '--fast' flag enables a faster, potentially less accurate, segmentation mode. ```bash docker run --gpus 'device=0' --ipc=host -v /home/ubuntu/test:/workspace totalsegmentator:master TotalSegmentator -i /workspace/ct3mm_0000.nii.gz -o /workspace/test_output --fast --preview ``` -------------------------------- ### Removing All Untagged Docker Images Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md This command removes all Docker images that do not have a tag (often referred to as '' images). These are typically intermediate images from build processes or dangling images. ```bash docker rmi $(docker images | grep "" | awk '{print $3}') ``` -------------------------------- ### Forcefully Stopping All Running Docker Containers Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md This command forcefully stops all currently running Docker containers. Use with caution as it will terminate all active containers immediately without saving state. ```bash docker kill $(docker ps -q) ``` -------------------------------- ### Terraform Infrastructure Destruction Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md This Terraform command destroys all infrastructure defined in the configuration. It is used to clean up resources. Running with '-auto-approve' will proceed with deletion without prompting for confirmation. ```bash terraform destroy -auto-approve ``` -------------------------------- ### Detect CT Contrast Phase using CLI and Python API Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt This section covers detecting the contrast enhancement phase in CT scans. It includes command-line usage of `totalseg_get_phase` with options for GPU/CPU and quiet mode, along with a Python API example using `get_ct_contrast_phase`. The output is a JSON containing phase information, timing, and probability. The function expects a nibabel image object as input. ```bash # Detect contrast phase from CT scan totalseg_get_phase \ -i /data/ct_with_contrast.nii.gz \ -o /results/phase_result.json \ --device gpu # CPU mode for systems without GPU totalseg_get_phase \ -i ct_scan.nii.gz \ -o phase.json \ --device cpu \ --quiet ``` ```python from totalsegmentator.bin.totalseg_get_phase import get_ct_contrast_phase import nibabel as nib import json ct_img = nib.load("/data/ct_contrast.nii.gz") result = get_ct_contrast_phase(ct_img, quiet=False, device="gpu") print(f"Detected phase: {result['phase']}") print(f"PI time: {result['pi_time']} seconds") print(f"Confidence: {result['probability']:.2%}") ``` -------------------------------- ### Checking Systemd Service Status Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md This command checks the current status of a systemd service, indicating whether it is active, inactive, or has encountered errors. It is crucial for monitoring service health. ```bash systemctl status totalsegmentator_server ``` -------------------------------- ### Updating and Redeploying TotalSegmentator Docker Container Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/server_setup.md Commands to update the TotalSegmentator code on the server, stop and remove the old container, build a new Docker image, and run it with persistent storage and GPU access. This ensures the latest code is running in production. ```bash cd ~/dev/TotalSegmentator git pull docker stop totalsegmentator-server-job docker rm $(docker ps -a -q -f status=exited) docker build -t totalsegmentator:master . docker run -d --restart always -p 80:5000 --gpus 'device=0' --ipc=host --name totalsegmentator-server-job -v /home/ubuntu/store:/app/store totalsegmentator:master /app/run_server.sh ``` -------------------------------- ### Set and Verify License for Commercial Models Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt This snippet explains how to set a license number for commercial segmentation tasks in TotalSegmentator. It covers the command-line tool to set the license, where the configuration is stored, and how to verify the license status. It also provides a Python API example for using a license during segmentation. ```bash # Set license number for commercial models totalseg_set_license --license_number ABC-123-XYZ-456 # License stored in ~/.totalsegmentator/config.json # Required for tasks: appendicular_bones, tissue_types, # heartchambers_highres, face, vertebrae_body, brain_structures, # coronary_arteries, and other commercial models # Verify license status cat ~/.totalsegmentator/config.json # Example config.json: # { # "license_number": "ABC-123-XYZ-456", # "statistics_disclaimer_shown": true # } ``` ```python from totalsegmentator.python_api import totalsegmentator totalsegmentator( input="ct_scan.nii.gz", output="output/", task="appendicular_bones", # requires license license_number="ABC-123-XYZ-456", device="gpu" ) ``` -------------------------------- ### Detect Imaging Modality (CT/MR) using CLI and Python API Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt This snippet details the detection of imaging modality (CT or MR) from scans. It shows command-line usage of `totalseg_get_modality` with options for normalized intensities and device selection, along with Python API examples using `get_modality` and `get_modality_from_rois`. The output is a JSON indicating the detected modality and its probability. The Python functions accept nibabel image objects. ```bash # Detect modality from scan (CT vs MR) totalseg_get_modality \ -i /data/unknown_scan.nii.gz \ -o /results/modality.json # Use normalized intensities for preprocessed images totalseg_get_modality \ -i preprocessed_scan.nii.gz \ -o modality.json \ --normalized_intensities \ --device gpu ``` ```python from totalsegmentator.bin.totalseg_get_modality import get_modality import nibabel as nib img = nib.load("/data/scan.nii.gz") result = get_modality(img) if result["modality"] == "ct": print(f"CT scan detected (confidence: {result['probability']:.2%})") else: print(f"MR scan detected (confidence: {result['probability']:.2%})") # For normalized images, use get_modality_from_rois from totalsegmentator.bin.totalseg_get_modality import get_modality_from_rois result = get_modality_from_rois(img, device="gpu") print(f"Modality: {result['modality']}, Probability: {result['probability']}") ``` -------------------------------- ### Interface Files (XIB) Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/README.md These are the Interface Builder files (.xib) used to define the user interface elements for the plugin's settings and segmentation run windows. They describe the layout and components of the UI. ```xml // Settings.xib // RunSegmentationWindowController.xib ``` -------------------------------- ### Update Version and Publish to PyPI Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/package_management.md Commands to update the project's version number in setup.py and CHANGELOG.md, commit changes, push to origin, tag the new version, and upload the distribution packages to PyPI using twine. This process is now automated by release.sh. ```bash git add . git commit -m "increase version to 1.5.1" git push git tag -a v1.5.1 -m "version 1.5.1" git push origin --tags python setup.py sdist bdist_wheel twine upload --skip-existing dist/* ``` -------------------------------- ### Download Pretrained Weights Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt Utility to download pretrained neural network weights for various TotalSegmentator tasks, enabling offline use and different segmentation models. ```APIDOC ## Download Pretrained Weights ### Description Fetch neural network weights for specific segmentation tasks. ### Method CLI command ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```bash # Download weights for total segmentation task (all organs) totalseg_download_weights --task total # Download fast model weights (lower resolution, faster inference) totalseg_download_weights --task total_fast # Download MR-specific models totalseg_download_weights --task total_mr # Download specialized task weights totalseg_download_weights --task lung_vessels totalseg_download_weights --task brain_structures totalseg_download_weights --task coronary_arteries # Download all available models (requires significant disk space) totalseg_download_weights --task all ``` ### Response #### Success Response (200) Pretrained weights are downloaded and stored in `~/.totalsegmentator/nnunet/results/`. #### Response Example ``` Weights stored in: ~/.totalsegmentator/nnunet/results/ ``` ``` -------------------------------- ### Run Pre-commit Checks Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/package_management.md Executes all pre-commit hooks on all files in the repository to ensure code quality and consistency before committing. ```bash pre-commit run --all-files ``` -------------------------------- ### Release New Weights (Manual Steps) Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/package_management.md Provides manual steps for releasing new model weights. This includes copying weight data, anonymizing nnUNet pickle files, zipping the dataset, and uploading the archive as a new release on GitHub. ```bash cd /mnt/nvme/data/multiseg/weights_upload/totalsegmentator_v2 cp -r $nnUNet_results/Dataset527_breasts_1559subj . python ~/dev/TotalSegmentator/resources/anonymise_nnunet_pkl_v2.py Dataset527_breasts_1559subj/nnUNetTrainer_DASegOrd0_NoMirroring__nnUNetPlans__3d_fullres zip -r Dataset527_breasts_1559subj.zip Dataset527_breasts_1559subj ``` -------------------------------- ### TotalSegmentator CLI for Image Segmentation Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt Provides a full-featured command-line interface for segmenting CT and MR images using over 104 anatomical classes. Supports various tasks, ROI subsetting, statistics generation, DICOM RT-Struct output, and MR-specific segmentation with robust cropping. It can run on CPU or GPU. ```bash TotalSegmentator -i /path/to/input.nii.gz -o /path/to/output_dir TotalSegmentator -i ct_scan.nii.gz -o results/ --fast --device cpu TotalSegmentator \ -i patient_scan.nii.gz \ -o segmentation_output/ \ --task lung_vessels \ --roi_subset lung_upper_lobe_left lung_lower_lobe_left \ --statistics \ --device gpu TotalSegmentator \ -i /dicom/series/folder/ \ -o rt_struct_output/ \ --output_type dicom \ --ml \ --preview TotalSegmentator \ -i mri_t1.nii.gz \ -o mri_output/ \ --task body_mr \ --robust_crop \ --device mps # Expected output structure: # output_dir/ # ├── liver.nii.gz # ├── spleen.nii.gz # ├── kidney_left.nii.gz # ├── kidney_right.nii.gz # ├── heart.nii.gz # └── ... (104 anatomical structures) ``` -------------------------------- ### Release New Weights (Automated) Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/package_management.md Initiates the release process for new model weights by running a preparation script. This is the recommended method for preparing weights for release. ```bash ./resources/prepare_weights_for_release.sh DATASET_ID [DATASET_ID2 ...] ``` -------------------------------- ### Download Pretrained Model Weights Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt Utility to download pre-trained neural network weights for various TotalSegmentator segmentation tasks. Supports specific tasks, fast models, MR models, and all available models. Weights are stored in `~/.totalsegmentator/nnunet/results/`. ```bash totalseg_download_weights --task total totalseg_download_weights --task total_fast totalseg_download_weights --task total_mr totalseg_download_weights --task lung_vessels totalseg_download_weights --task brain_structures totalseg_download_weights --task coronary_arteries totalseg_download_weights --task all # Weights stored in: ~/.totalsegmentator/nnunet/results/ ``` -------------------------------- ### Core Plugin Logic (Swift) Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/README.md This indicates the primary file containing the core logic for the TotalSegmentator Horos Plugin, written in Swift. It would handle interactions with Horos and the Python backend. ```swift // MyOsiriXPluginFolder-Swift/Plugin.swift ``` -------------------------------- ### Command-Line Interface: TotalSegmentator Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt The TotalSegmentator CLI allows for full-featured segmentation of CT/MR images with over 104 anatomical classes directly from the command line. ```APIDOC ## Command-Line Interface: TotalSegmentator ### Description Full-featured CLI for segmenting CT/MR images with 104+ anatomical classes. ### Method CLI command ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```bash # Basic usage - segment CT image with default total task on GPU TotalSegmentator -i /path/to/input.nii.gz -o /path/to/output_dir # Fast mode with CPU device for quick results at lower resolution TotalSegmentator -i ct_scan.nii.gz -o results/ --fast --device cpu # Specific task with ROI subset and statistics generation TotalSegmentator \ -i patient_scan.nii.gz \ -o segmentation_output/ \ --task lung_vessels \ --roi_subset lung_upper_lobe_left lung_lower_lobe_left \ --statistics \ --device gpu # DICOM RT-Struct output with multilabel mask TotalSegmentator \ -i /dicom/series/folder/ \ -o rt_struct_output/ \ --output_type dicom \ --ml \ --preview # MR body segmentation with robust cropping TotalSegmentator \ -i mri_t1.nii.gz \ -o mri_output/ \ --task body_mr \ --robust_crop \ --device mps ``` ### Response #### Success Response (200) Output is saved to the specified directory, containing NIfTI files for each segmented anatomical structure. #### Response Example ``` output_dir/ ├── liver.nii.gz ├── spleen.nii.gz ├── kidney_left.nii.gz ├── kidney_right.nii.gz ├── heart.nii.gz └── ... (104 anatomical structures) ``` ``` -------------------------------- ### Advanced Segmentation: Memory, Cropping, and Quality Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt This Python code demonstrates advanced TotalSegmentator configurations. It includes options for forcing image splitting to manage memory, enabling automatic body segmentation with cropping, applying higher-order resampling for improved quality, saving probability maps for uncertainty analysis, and performing statistics with normalized intensities. ```python from totalsegmentator.python_api import totalsegmentator from pathlib import Path import nibabel as nib # Force split for large images (reduce memory consumption) totalsegmentator( input=Path("large_ct_scan.nii.gz"), output=Path("output/"), force_split=True, # process in 3 chunks nr_thr_resamp=4, # parallel resampling threads nr_thr_saving=8, # parallel saving threads device="gpu" ) # Body segmentation with automatic cropping totalsegmentator( input="full_body_ct.nii.gz", output="body_output/", body_seg=True, # initial rough body segmentation crop_path=Path("crop_masks/"), # custom crop mask location robust_crop=True, # use 3mm model for accurate cropping device="gpu" ) # Higher quality resampling for high-resolution images totalsegmentator( input="highres_ct.nii.gz", output="highres_output/", higher_order_resampling=True, # smoother segmentations remove_small_blobs=True, # remove components <0.2ml device="gpu" ) # Save probability maps for uncertainty analysis totalsegmentator( input="ct_scan.nii.gz", output="output/", save_probabilities=Path("probabilities/"), device="gpu" ) # Creates probability maps for each class (advanced usage) # Statistics with normalized intensities totalsegmentator( input="normalized_ct.nii.gz", output="stats_output/", statistics=True, statistics_normalized_intensities=True, statistics_exclude_masks_at_border=True, device="gpu" ) ``` -------------------------------- ### Combine Masks using CLI and Python API Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt This snippet demonstrates how to combine segmentation masks using the `totalseg_combine_masks` command-line tool and its equivalent Python API. It allows for combining predefined structures like 'vertebrae_ribs' and 'pelvis', or custom lists of classes. Input is a directory of masks, and output is a single combined mask image. ```bash totalseg_combine_masks \ -i /results/patient_001/ \ -o /results/patient_001/spine_ribs.nii.gz \ -m vertebrae_ribs totalseg_combine_masks \ -i /results/patient_001/ \ -o /results/patient_001/pelvis.nii.gz \ -m pelvis ``` ```python from totalsegmentator.libs import combine_masks from pathlib import Path import nibabel as nib mask_dir = Path("/results/patient_001/") combined_img = combine_masks(mask_dir, "lung") ib.save(combined_img, "/results/patient_001/lung_combined.nii.gz") custom_classes = ["liver", "spleen", "pancreas"] combined_img = combine_masks(mask_dir, custom_classes) ib.save(combined_img, "/results/patient_001/abdominal_organs.nii.gz") ``` -------------------------------- ### Python API: totalsegmentator() Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt Programmatic segmentation interface for integration into Python workflows, allowing direct processing of image data or file paths. ```APIDOC ## Python API: totalsegmentator() ### Description Programmatic segmentation interface for integration into Python workflows. ### Method Python function call ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python from pathlib import Path import nibabel as nib from totalsegmentator.python_api import totalsegmentator # Segment from file path with statistics input_path = Path("/data/patient_001_ct.nii.gz") output_dir = Path("/results/patient_001/") output_dir.mkdir(parents=True, exist_ok=True) seg_img = totalsegmentator( input=input_path, output=output_dir, task="total", fast=False, device="gpu", statistics=True, ml=True ) # seg_img is a nibabel Nifti1Image with multilabel segmentation # statistics.json created in output_dir with volumes and intensities # Process nibabel image directly without file I/O ct_img = nib.load("/data/scan.nii.gz") seg_result = totalsegmentator( input=ct_img, output=None, task="lung_vessels", roi_subset=["lung_upper_lobe_left", "lung_lower_lobe_left"], fast=True, device="cpu", skip_saving=True ) # Returns multilabel image, no files written (skip_saving=True) seg_data = seg_result.get_fdata() print(f"Segmentation shape: {seg_data.shape}") print(f"Unique labels: {set(seg_data.flatten())}") # Radiomics feature extraction totalsegmentator( input=Path("ct_with_contrast.nii.gz"), output=Path("radiomics_output/"), task="liver_vessels", radiomics=True, statistics=True, device="gpu:0" ) # Creates statistics_radiomics.json with pyradiomics features ``` ### Response #### Success Response (200) Returns a nibabel Nifti1Image object containing the segmentation results. If `output` is specified and `skip_saving` is False, the result is also saved to disk. Statistics and radiomics results are saved to JSON files if requested. #### Response Example ```json { "segmentation_image": "nibabel.nifti1.Nifti1Image", "statistics.json": "(optional, if statistics=True)", "statistics_radiomics.json": "(optional, if radiomics=True)" } ``` ``` -------------------------------- ### Combine Masks Utility Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt A utility script to merge individual organ segmentation masks into unified binary masks for specific anatomical regions. ```APIDOC ## Combine Masks Utility ### Description Merge individual organ masks into unified binary masks. ### Method CLI command ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```bash # Combine all lung lobes into single lung mask totalseg_combine_masks \ -i /results/patient_001/ \ -o /results/patient_001/lung_combined.nii.gz \ -m lung # Combine left lung only totalseg_combine_masks \ -i /results/patient_001/ \ -o /results/patient_001/lung_left.nii.gz \ -m lung_left ``` ### Response #### Success Response (200) A new NIfTI file is created at the specified output path containing the combined mask. #### Response Example ``` /results/patient_001/lung_combined.nii.gz /results/patient_001/lung_left.nii.gz ``` ``` -------------------------------- ### Python API for Medical Image Segmentation Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt A programmatic interface for integrating TotalSegmentator into Python workflows. It allows segmentation from file paths or directly from nibabel images, with options for various tasks, ROI filtering, and output types. Supports statistics generation, radiomics feature extraction, and can run on CPU or GPU. ```python from pathlib import Path import nibabel as nib from totalsegmentator.python_api import totalsegmentator # Segment from file path with statistics input_path = Path("/data/patient_001_ct.nii.gz") output_dir = Path("/results/patient_001/") output_dir.mkdir(parents=True, exist_ok=True) seg_img = totalsegmentator( input=input_path, output=output_dir, task="total", fast=False, device="gpu", statistics=True, ml=True ) # seg_img is a nibabel Nifti1Image with multilabel segmentation # statistics.json created in output_dir with volumes and intensities # Process nibabel image directly without file I/O ct_img = nib.load("/data/scan.nii.gz") seg_result = totalsegmentator( input=ct_img, output=None, task="lung_vessels", roi_subset=["lung_upper_lobe_left", "lung_lower_lobe_left"], fast=True, device="cpu", skip_saving=True ) # Returns multilabel image, no files written (skip_saving=True) seg_data = seg_result.get_fdata() print(f"Segmentation shape: {seg_data.shape}") print(f"Unique labels: {set(seg_data.flatten())}") # Radiomics feature extraction totalsegmentator( input=Path("ct_with_contrast.nii.gz"), output=Path("radiomics_output/"), task="liver_vessels", radiomics=True, statistics=True, device="gpu:0" ) # Creates statistics_radiomics.json with pyradiomics features ``` -------------------------------- ### Utility to Combine Segmentation Masks Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt Combines individual anatomical masks generated by TotalSegmentator into unified binary masks. Useful for grouping related structures like all lung lobes into a single lung mask. Takes input directory and specifies output file and the mask to combine. ```bash totalseg_combine_masks \ -i /results/patient_001/ \ -o /results/patient_001/lung_combined.nii.gz \ -m lung totalseg_combine_masks \ -i /results/patient_001/ \ -o /results/patient_001/lung_left.nii.gz \ -m lung_left ``` -------------------------------- ### Task Dictionary Mapping Source: https://context7.com/thalesmms/totalsegmentator-horos-plugin/llms.txt This dictionary maps task names to descriptions of the anatomical structures or regions they segment. It is used to select specific segmentation tasks within the TotalSegmentator library. ```python tasks = { "total": "104 anatomical structures (1.5mm resolution)", "body": "Body regions and extremities", "body_mr": "MR body segmentation", "vertebrae_mr": "MR vertebrae segmentation", "lung_vessels": "Pulmonary vasculature", "cerebral_bleed": "Intracranial hemorrhage detection", "hip_implant": "Hip prosthesis segmentation", "coronary_arteries": "Coronary artery tree", "pleural_pericard_effusion": "Fluid collections", "appendicular_bones": "Limb skeleton", "tissue_types": "Tissue classification", "heartchambers_highres": "Cardiac chambers (high resolution)", "face": "Facial structures", "vertebrae_body": "Vertebral bodies with discs", "total_mr": "MR multi-organ segmentation", "tissue_types_mr": "MR tissue classification", "tissue_4_types": "4-class tissue segmentation", "face_mr": "MR facial structures", "head_glands_cavities": "Salivary glands, sinuses", "head_muscles": "Cranial musculature", "headneck_bones_vessels": "Skull and neck vessels", "headneck_muscles": "Neck musculature", "brain_structures": "Neuroanatomical structures", "liver_vessels": "Hepatic vasculature", "oculomotor_muscles": "Extraocular muscles", "thigh_shoulder_muscles": "Limb musculature", "lung_nodules": "Pulmonary nodule detection", "kidney_cysts": "Renal cyst segmentation", "breasts": "Breast tissue segmentation", "ventricle_parts": "Ventricular substructures", "aortic_sinuses": "Aortic root structures", "liver_segments": "Couinaud liver segments", "abdominal_muscles": "Abdominal wall musculature", "teeth": "Dental structures" } ``` -------------------------------- ### TotalSegmentator Structures for Contrast Phase Prediction Source: https://github.com/thalesmms/totalsegmentator-horos-plugin/blob/main/resources/contrast_phase_prediction.md This snippet lists the anatomical structures predicted by TotalSegmentator that are used as features for the contrast phase classifier. The median intensity (HU value) of these predicted structures is calculated. ```python ["liver", "pancreas", "urinary_bladder", "gallbladder", "heart", "aorta", "inferior_vena_cava", "portal_vein_and_splenic_vein", "iliac_vena_left", "iliac_vena_right", "iliac_artery_left", "iliac_artery_right", "pulmonary_vein", "brain", "colon", "small_bowel", "internal_carotid_artery_right", "internal_carotid_artery_left", "internal_jugular_vein_right", "internal_jugular_vein_left"] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.