### Basic AutoPipeline Usage Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/autopipeline.md Demonstrates the fundamental command structure for AutoPipeline, specifying modalities and input/output directories. This is the starting point for most processing tasks. ```bash imgtools autopipeline \ --modalities CT,RTSTRUCT \ /path/to/messy/dicoms/ \ /path/to/output/ ``` -------------------------------- ### Example: Using ROIMatcher for Merging ROIs Source: https://github.com/bhklab/med-imagetools/blob/main/src/imgtools/coretypes/Mask_VectorMask.md Demonstrates the usage of the `ROIMatcher` class with the `ROIMatchStrategy.MERGE` strategy. This example shows how to initialize the matcher to group ROIs matching a pattern (e.g., 'GTV.*') under a common key ('GTV'), ignoring case. It highlights a scenario where multiple disconnected objects can exist under a single matched key after processing. ```python matcher = ROIMatcher( match_map={"GTV": ["GTV.*"]}, handling_strategy=ROIMatchStrategy.MERGE, ignore_case=True, # important for matching lowercase labels ) # Mapped: (roi_key='GTV', roi_names=['GTV-2', 'GTV-1']) ### .... vector extracted mask logic to get scalar mask # this mask only has 1 label, but 4 objects cc = sitk.ConnectedComponentImageFilter() cc.Execute(extracted_scalar_mask) cc.GetObjectCount() # Output: 4 ``` -------------------------------- ### Run nnunet-pipeline CLI with region_mask strategy Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/nnunet_pipeline.md This example demonstrates how to run the nnunet-pipeline command-line interface for processing medical images. It specifies the modalities, ROI matching configuration, and the desired mask-saving strategy ('region_mask'). The command takes input DICOM directory and output directory as arguments. ```bash imgtools nnunet-pipeline \ --modalities CT,RTSTRUCT \ --roi-match-yaml roi_patterns.yaml \ --mask-saving-strategy region_mask \ /data/dicoms/ \ /data/nnunet_ready/ ``` -------------------------------- ### Install med-imagetools Source: https://github.com/bhklab/med-imagetools/blob/main/README.md Installs the med-imagetools package using pip. It also shows how to access the command-line help for the 'imgtools' command. An alternative installation using 'uvx' with all optional dependencies is also demonstrated. ```console pip install med-imagetools imgtools --help ``` ```console uvx --from 'med-imagetools[all]' imgtools --help ``` -------------------------------- ### Install Fish Shell Completion for imgtools Source: https://github.com/bhklab/med-imagetools/blob/main/docs/cli/shell-completion.md Installs shell completion for the imgtools CLI in fish. This involves sourcing the completion script for the current session and placing the script in the appropriate directory for permanent setup. ```fish imgtools shell-completion fish | source # For permanent setup: mkdir -p ~/.config/fish/completions imgtools shell-completion fish > ~/.config/fish/completions/imgtools.fish ``` -------------------------------- ### Initialize Writer with Root Directory and Filename Format (Python) Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/Writers/BaseWriter.md Demonstrates how to initialize a writer with a root directory and a filename format string. The filename format uses placeholders that are dynamically filled with context variables during the save operation. This example assumes an `ExampleWriter` class that extends `AbstractBaseWriter`. ```python writer = ExampleWriter( root_directory="./data", filename_format="{person_name}/{date}_{message_type}.txt", ) # Save a file with context variables data = "Hello, World!" writer.save( data, person_name="JohnDoe", date="2025-01-01", message_type="greeting" ) # Saved file path: # ./data/JohnDoe/2025-01-01_greeting.txt ``` -------------------------------- ### Install Bash Shell Completion for imgtools Source: https://github.com/bhklab/med-imagetools/blob/main/docs/cli/shell-completion.md Installs shell completion for the imgtools CLI in bash. This involves sourcing the completion script for the current session and optionally adding it to ~/.bashrc for permanent setup. ```bash source <(imgtools shell-completion bash) # For permanent setup: mkdir -p ~/.bash_completion.d imgtools shell-completion bash > ~/.bash_completion.d/imgtools echo 'source ~/.bash_completion.d/imgtools' >> ~/.bashrc source ~/.bashrc ``` -------------------------------- ### Install Zsh Shell Completion for imgtools Source: https://github.com/bhklab/med-imagetools/blob/main/docs/cli/shell-completion.md Installs shell completion for the imgtools CLI in zsh. This involves sourcing the completion script for the current session and configuring ~/.zshrc for permanent setup. ```zsh source <(imgtools shell-completion zsh) # For permanent setup: mkdir -p ~/.zsh/completion imgtools shell-completion zsh > ~/.zsh/completion/_imgtools echo 'fpath=(~/.zsh/completion $fpath)' >> ~/.zshrc echo 'autoload -U compinit && compinit' >> ~/.zshrc source ~/.zshrc ``` -------------------------------- ### Using Writer with Context Manager (Python) Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/Writers/BaseWriter.md Illustrates the use of the `AbstractBaseWriter` (or its subclasses like `TextWriter`) as a context manager. This ensures proper setup and cleanup, including removing lock files and deleting empty directories upon exiting the `with` block. ```python with TextWriter(root_directory="/data", filename_format="{id}.txt") as writer: data = "Hello, World!" writer.save(data, id="1234") ``` -------------------------------- ### Examples of Invalid ROI Matcher Inputs Source: https://github.com/bhklab/med-imagetools/blob/main/src/imgtools/coretypes/masktypes/README.md Demonstrates invalid configurations for the `roi_matcher` input. These examples highlight incorrect data types (integer) and improper nesting (list of lists, dictionary within a dictionary). ```python roi_matcher = 123 # invalid (not str/list/dict) roi_matcher = [["GTV.*", "CTV.*"]] # invalid (nested list) roi_matcher = {"GTV": {"GTVp": "GTVp.*"}} # invalid (nested dict) ``` -------------------------------- ### Examples of Valid ROI Matcher Inputs Source: https://github.com/bhklab/med-imagetools/blob/main/src/imgtools/coretypes/masktypes/README.md Illustrates valid ways to define the `roi_matcher` input for ROI matching. This includes using a single string pattern, a list of patterns, or a dictionary mapping keys to lists of patterns. ```python roi_matcher = "GTV.*" # → {"ROI": ["GTV.*"]} roi_matcher = ["GTVp", "CTV.*"] # → {"ROI": ["GTVp", "CTV.*"]} roi_matcher = {"GTV": ["GTVp", "CTV.*"]} roi_matcher = {"GTV": ["GTV.*"], "CTV": ["CTV.*"]} ``` -------------------------------- ### Python: Implement Save Method for Custom Writer with Path Handling Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/Writers/ImplementingWriters.md This Python example shows a detailed implementation of the 'save' method for a custom writer extending AbstractBaseWriter. It includes path resolution using 'resolve_path', optional handling for existing files based on skip mode, writing content, and comprehensive logging with 'add_to_index'. ```python from pathlib import Path from mypackage.abstract_base_writer import AbstractBaseWriter class MyCustomWriter(AbstractBaseWriter[str]): def save(self, content: str, **kwargs) -> Path: # Step 1: Resolve the output file path # you can try-catch this in case set to "FAIL" mode # or just let the error propagate output_path = self.resolve_path(**kwargs) # resolve_path will always return the path # OPTIONAL handling for "SKIP" modes if output_path.exists(): # this will only be true if the file existence mode # is set to SKIP # - OVERWRITE will have already deleted the file # - upto developer to choose to handle this if set to SKIP pass # Step 2: Write the content to the resolved path with output_path.open(mode="w", encoding="utf-8") as f: f.write(content) # Step 3: Log and track the save operation self.add_to_index( path=output_path, include_all_context=True, filepath_column="filepath", replace_existing=False, merge_columns=True, ) # Step 4: ALWAYS Return the saved file path return output_path ``` -------------------------------- ### Image Transformation Pipeline with Transformer in Python Source: https://context7.com/bhklab/med-imagetools/llms.txt Demonstrates the creation and application of image transformations using the Transformer class. It includes examples of Resample, WindowIntensity, Crop, and ClipIntensity transformations, along with loading scan data. ```python from imgtools.transforms import ( Resample, Resize, Crop, Rotate, Zoom, WindowIntensity, ClipIntensity, Transformer ) from imgtools.coretypes import Scan import numpy as np # Load images (example) # ct_scan = Scan.from_dicom("/data/CT") # vector_mask = rtstruct.get_vector_mask(ct_scan, roi_matcher) # Assuming these are defined # Create individual transforms resample_transform = Resample( spacing=(1.0, 1.0, 1.0), interpolation="linear", anti_alias=True, ) window_transform = WindowIntensity( window=400, # HU window width level=40, # HU window center ) crop_transform = Crop( crop_centre=(0, 0, 0), size=(256, 256, 128), mode="constant", constant_value=0, ) clip_transform = ClipIntensity( lower=-1000, # Minimum HU upper=3000, # Maximum HU ) # Example of creating a Transformer and applying it (commented out as full context is missing) # transformer = Transformer([ # resample_transform, # window_transform, # crop_transform, # clip_transform # ]) # transformed_scan = transformer.apply(ct_scan) ``` -------------------------------- ### AutoPipeline with Transformations Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/autopipeline.md Shows how to apply transformations during the AutoPipeline process, such as setting image spacing and window level/width. These transformations modify the image properties in the output. ```bash imgtools autopipeline\ --modalities CT,RTSTRUCT \ --spacing 1.0,1.0,1.0 \ --window-width 400 --window-level 40 \ /path/to/dicoms/ \ /path/to/output/ ``` -------------------------------- ### Initialize TextWriter with Context Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/Writers/BaseWriter.md Demonstrates initializing a TextWriter with a predefined set of context variables passed as a dictionary to the `context` parameter. This is useful when most save operations share the same context. ```python writer = TextWriter( root_directory="./data", filename_format="{class_subject}/{person_name}/{date}_{message_type}.txt", context={"grade": "12", "class_subject": "math", "date": "2025-01-01", "message_type": "greeting"} ) student, message = "Alice", "Hello, Alice!" writer.save(message, person_name=student) student, message = "Bob", "Good morning, Bob!" writer.save(message, person_name=student) ``` -------------------------------- ### AutoPipeline Parallel Processing Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/autopipeline.md Demonstrates how to leverage parallel processing in AutoPipeline using the `--jobs` option. This feature significantly speeds up processing for large datasets by utilizing multiple CPU cores. ```bash imgtools autopipeline /path/to/dicoms/ /path/to/output/ \ --modalities CT,RTSTRUCT \ --jobs 8 # Use 8 parallel processes ``` -------------------------------- ### Initialize TextWriter with Filename Format Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/Writers/BaseWriter.md Initializes a TextWriter instance with a specified root directory and filename format. The filename format uses placeholders for context variables. ```python writer = TextWriter( root_directory="./data", filename_format="{grade}/{class_subject}/{person_name}/{date}_{message_type}.txt", ) ``` -------------------------------- ### AutoPipeline Handling Existing Files Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/autopipeline.md Illustrates the `--existing-file-mode` option in AutoPipeline, which controls behavior when output files already exist. Options include skipping, overwriting, or failing the process. ```bash imgtools autopipeline /path/to/dicoms/ /path/to/output/ \ --modalities CT,RTSTRUCT \ --existing-file-mode skip # Options: skip, overwrite, fail ``` -------------------------------- ### Import Image Generation and Visualization Libraries Source: https://github.com/bhklab/med-imagetools/blob/main/devnotes/transform_notebooks/transforms.ipynb Imports necessary libraries from SimpleITK and the imgtools package for image creation and visualization. It includes functions for creating spheres, grids, gradients, crosses, rods, noisy spheres, checkerboards, and CT Hounsfield images, along with an ImageVisualizer class and a display_slices function. ```python import SimpleITK as sitk from imgtools.datasets.sample_images import ( create_sphere_image, create_grid_image, create_gradient_image, create_cross_image, create_rod_image, create_noisy_sphere_image, create_checkerboard_image, create_ct_hounsfield_image, ) from imgtools.vizualize import ( ImageVisualizer, display_slices, ) ``` -------------------------------- ### Basic Autopipeline Usage for DICOM Processing Source: https://context7.com/bhklab/med-imagetools/llms.txt This command shows the fundamental usage of the `imgtools autopipeline` command. It specifies the modalities to process (CT, RTSTRUCT) and the input and output directories. This is the starting point for batch processing DICOM datasets. ```bash # Basic autopipeline usage imgtools autopipeline \ --modalities CT,RTSTRUCT \ /data/raw_dicoms/ \ /data/processed/ ``` -------------------------------- ### Load and Process DICOM RT Structure Sets Source: https://context7.com/bhklab/med-imagetools/llms.txt Illustrates how to load DICOM RT structure sets using `RTStructureSet.from_dicom`. The library supports flexible ROI extraction and mask generation, although specific mask generation examples are not shown here. ```python from imgtools.coretypes import RTStructureSet, Scan from imgtools.coretypes.masktypes import ROIMatcher, ROIMatchStrategy, ROIMatchFailurePolicy # Load structure set rtstruct = RTStructureSet.from_dicom("/data/PATIENT001/RTSTRUCT/struct.dcm") ``` -------------------------------- ### AutoPipeline ROI Standardization via YAML Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/autopipeline.md Explains how to standardize ROI names using a YAML configuration file with the `--roi-match-yaml` option. This method is useful for managing complex or numerous ROI mapping rules. ```yaml # roi_patterns.yaml GTV: ["GTV", "gtv", "Gross.*Volume"] Parotid_L: ["LeftParotid", "PAROTID_L", "L_Parotid"] Parotid_R: ["RightParotid", "PAROTID_R", "R_Parotid"] Cord: ["SpinalCord", "Cord", "Spinal_Cord"] Mandible: ["mandible.*"] ``` ```bash imgtools autopipeline\ --modalities CT,RTSTRUCT \ --roi-match-yaml roi_patterns.yaml ``` -------------------------------- ### Universal DICOM Loader with read_dicom_auto Source: https://context7.com/bhklab/med-imagetools/llms.txt Provides examples for using `read_dicom_auto` to automatically detect DICOM modality and load files with appropriate class handling. It covers loading various modalities like CT, PET, RTSTRUCT, RTDOSE, and SEG, and converting them to NumPy arrays. ```python from imgtools.io.readers import read_dicom_auto # Load CT scan (auto-detects modality) ct_scan = read_dicom_auto("/data/PATIENT001/CT") print(f"Loaded {ct_scan.metadata['Modality']} scan") print(f"Size: {ct_scan.size}, Spacing: {ct_scan.spacing}") # Load with explicit modality pet_scan = read_dicom_auto("/data/PATIENT001/PET", modality="PT") # Load RT structure set rtstruct = read_dicom_auto("/data/PATIENT001/RTSTRUCT/file.dcm", modality="RTSTRUCT") print(f"ROIs available: {rtstruct.roi_names}") # Load dose distribution dose = read_dicom_auto("/data/PATIENT001/RTDOSE", modality="RTDOSE") print(f"Dose range: {dose.GetPixelIDTypeAsString()}") # Load segmentation seg = read_dicom_auto("/data/PATIENT001/SEG/seg.dcm", modality="SEG") # Convert to numpy array array, geometry = ct_scan.to_numpy() print(f"Array shape: {array.shape}") print(f"Geometry: origin={geometry.origin}, spacing={geometry.spacing}") # Access metadata print(f"Patient ID: {ct_scan.metadata['PatientID']}") print(f"Study Date: {ct_scan.metadata.get('StudyDate', 'N/A')}") ``` -------------------------------- ### AutoPipeline Custom Output Formatting Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/autopipeline.md Shows how to customize the output file naming convention using the `--filename-format` option. This allows for structured organization of processed data based on metadata. ```bash imgtools autopipeline /path/to/dicoms/ /path/to/output/ \ --modalities CT,RTSTRUCT \ --filename-format "{PatientID}/{Modality}/{ImageID}.nii.gz" ``` -------------------------------- ### Create Checkerboard Image and Visualize Source: https://github.com/bhklab/med-imagetools/blob/main/devnotes/transform_notebooks/transforms.ipynb Generates a checkerboard pattern image. The commented-out parameters indicate default values for size, spacing, and checker size. Visualization is done using interactive slices. Dependencies include image creation and visualization utilities. ```python checkerboard = create_checkerboard_image( # size=(100, 100, 100), # spacing=(1.0, 1.0, 1.0), # checker_size=10, ) viz = ImageVisualizer.from_image(checkerboard) viz.view_slices() ``` -------------------------------- ### Preview File Path with ExistingFileMode.SKIP Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/Writers/BaseWriter.md Illustrates using `preview_path()` with `ExistingFileMode.SKIP` to check for file existence. If the file exists, `preview_path()` returns `None`, allowing the program to skip computation and potentially avoid overwriting existing data. ```python # assuming writer is already initialized with `existing_file_mode=ExistingFileMode.SKIP` # set some context variables writer.set_context(class_subject="math", date="2025-01-01", message_type="greeting") if (path := writer.preview_path(person_name="Alice")) is None: print("File already exists, skipping computation.") else: print(f"Proceed with computation for {path}") ... # perform expensive computation ... writer.save(content="Hello, world!") ``` -------------------------------- ### Initialize and Draw Graph using vis.js Source: https://github.com/bhklab/med-imagetools/blob/main/docs/interlacer.html This function initializes a vis.js network graph with specified data, options, and a container element. It handles the drawing of nodes and edges, configures interaction and physics properties, and includes a loading bar to show the stabilization progress. The function returns the vis.js network instance. ```javascript function drawGraph() { var container = document.getElementById('graph'); var nodes = new vis.DataSet([{"id": "1.2.276.0.7230010.3.1.3.0.21098.1674505868.432864", "label": "Dicom", "color": "#ff0000", "shape": "dot", "size": 10},{"id": "61.7.195607731455189297340213752950162268655", "label": "Series", "color": "#00ff00", "shape": "dot", "size": 10},{"id": "1.2.276.0.7230010.3.1.3.0.21087.1674505858.27473", "label": "Dicom", "color": "#ff0000", "shape": "dot", "size": 10},{"id": "1.3.6.1.4.1.14519.5.2.1.303606626100058921970651747217776792853", "label": "Dicom", "color": "#ff0000", "shape": "dot", "size": 10},{"id": "61.7.167248355135476067044532759811631626828", "label": "Series", "color": "#00ff00", "shape": "dot", "size": 10},{"id": "1.3.6.1.4.1.14519.5.2.1.124502390760917755084744319866454742880", "label": "Series", "color": "#00ff00", "shape": "dot", "size": 10},{"id": "1.3.6.1.4.1.14519.5.2.1.87289399620455574127294995600028722208", "label": "Dicom", "color": "#ff0000", "shape": "dot", "size": 10},{"id": "1.3.6.1.4.1.14519.5.2.1.239064923357616718786196407609276882856", "label": "Dicom", "color": "#ff0000", "shape": "dot", "size": 10},{"id": "61.7.167248355135476067044532759811631626828", "label": "Series", "color": "#00ff00", "shape": "dot", "size": 10},{"id": "1.3.6.1.4.1.14519.5.2.1.326371846250448593750128054318722243822", "label": "Series", "color": "#00ff00", "shape": "dot", "size": 10},{"id": "1.3.6.1.4.1.14519.5.2.1.201470230935448347076675762989040304388", "label": "Dicom", "color": "#ff0000", "shape": "dot", "size": 10},{"id": "1.3.6.1.4.1.14519.5.2.1.100364245183930759730290495595573094436", "label": "Dicom", "color": "#ff0000", "shape": "dot", "size": 10},{"id": "1.3.6.1.4.1.14519.5.2.1.97824612055862366318560427964793890998", "label": "Series", "color": "#00ff00", "shape": "dot", "size": 10},{"id": "1.3.6.1.4.1.14519.5.2.1.151251643407469240433833224247202025725", "label": "Dicom", "color": "#ff0000", "shape": "dot", "size": 10},{"id": "1.3.6.1.4.1.14519.5.2.1.75164064738538288645257513911612519591", "label": "Dicom", "color": "#ff0000", "shape": "dot", "size": 10},{"id": "1.3.6.1.4.1.14519.5.2.1.149357697745643823053302398129943470751", "label": "Series", "color": "#00ff00", "shape": "dot", "size": 10},{"id": "1.3.6.1.4.1.14519.5.2.1.184635744045576879217642059609700669252", "label": "Dicom", "color": "#ff0000", "shape": "dot", "size": 10},{"id": "1.3.6.1.4.1.14519.5.2.1.75164064738538288645257513911612519591", "label": "Dicom", "color": "#ff0000", "shape": "dot", "size": 10}]); var edges = new vis.DataSet([{"arrows": "to", "from": "1.2.276.0.7230010.3.1.3.0.21098.1674505868.432864", "to": "61.7.195607731455189297340213752950162268655"}, {"arrows": "to", "from": "1.2.276.0.7230010.3.1.3.0.21087.1674505858.27473", "to": "61.7.167248355135476067044532759811631626828"}, {"arrows": "to", "from": "1.3.6.1.4.1.14519.5.2.1.303606626100058921970651747217776792853", "to": "1.3.6.1.4.1.14519.5.2.1.124502390760917755084744319866454742880"}, {"arrows": "to", "from": "1.3.6.1.4.1.14519.5.2.1.87289399620455574127294995600028722208", "to": "1.3.6.1.4.1.14519.5.2.1.303606626100058921970651747217776792853"}, {"arrows": "to", "from": "1.3.6.1.4.1.14519.5.2.1.239064923357616718786196407609276882856", "to": "1.3.6.1.4.1.14519.5.2.1.326371846250448593750128054318722243822"}, {"arrows": "to", "from": "1.3.6.1.4.1.14519.5.2.1.201470230935448347076675762989040304388", "to": "1.3.6.1.4.1.14519.5.2.1.239064923357616718786196407609276882856"}, {"arrows": "to", "from": "1.3.6.1.4.1.14519.5.2.1.100364245183930759730290495595573094436", "to": "1.3.6.1.4.1.14519.5.2.1.97824612055862366318560427964793890998"}, {"arrows": "to", "from": "1.3.6.1.4.1.14519.5.2.1.151251643407469240433833224247202025725", "to": "1.3.6.1.4.1.14519.5.2.1.100364245183930759730290495595573094436"}, {"arrows": "to", "from": "1.3.6.1.4.1.14519.5.2.1.75164064738538288645257513911612519591", "to": "1.3.6.1.4.1.14519.5.2.1.149357697745643823053302398129943470751"}, {"arrows": "to", "from": "1.3.6.1.4.1.14519.5.2.1.184635744045576879217642059609700669252", "to": "1.3.6.1.4.1.14519.5.2.1.75164064738538288645257513911612519591"}]); var nodeColors = {}; allNodes = nodes.get({ returnType: "Object" }); for (nodeId in allNodes) { nodeColors[nodeId] = allNodes[nodeId].color; } allEdges = edges.get({ returnType: "Object" }); data = {nodes: nodes, edges: edges}; var options = { "configure": { "enabled": false }, "edges": { "color": { "inherit": true }, "smooth": { "enabled": true, "type": "dynamic" } }, "interaction": { "dragNodes": true, "hideEdgesOnDrag": false, "hideNodesOnDrag": false }, "physics": { "enabled": true, "forceAtlas2Based": { "avoidOverlap": 0, "centralGravity": 0.01, "damping": 0.4, "gravitationalConstant": -50, "springConstant": 0.08, "springLength": 100 }, "solver": "forceAtlas2Based", "stabilization": { "enabled": true, "fit": true, "iterations": 1000, "onlyDynamicEdges": false, "updateInterval": 50 } } }; network = new vis.Network(container, data, options); network.on("stabilizationProgress", function(params) { document.getElementById('loadingBar').removeAttribute("style"); var maxWidth = 496; var minWidth = 20; var widthFactor = params.iterations/params.total; var width = Math.max(minWidth,maxWidth * widthFactor); document.getElementById('bar').style.width = width + 'px'; document.getElementById('text').innerHTML = Math.round(widthFactor*100) + '%'; }); network.once("stabilizationIterationsDone", function() { document.getElementById('text').innerHTML = '100%'; document.getElementById('bar').style.width = '496px'; document.getElementById('loadingBar').style.opacity = 0; setTimeout(function () {document.getElementById('loadingBar').style.display = 'none';}, 500); }); return network; } drawGraph(); ``` -------------------------------- ### Basic TextWriter Save Operation Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/Writers/BaseWriter.md Demonstrates the basic usage of TextWriter's save method by passing all context variables as keyword arguments for each save operation. This can become verbose when context variables are repetitive. ```python student, message = "Alice", "Hello, Alice!" writer.save( message, person_name=student, grade="12", class_subject="math", date="2025-01-01", message_type="greeting" ) student, message = "Bob", "Good morning, Bob!" writer.save( message, person_name=student, grade="12", class_subject="math", date="2025-01-01", message_type="greeting" ) ``` -------------------------------- ### Create and Visualize Grid Image Source: https://github.com/bhklab/med-imagetools/blob/main/devnotes/transform_notebooks/transforms.ipynb Generates a grid phantom image using `create_grid_image` and visualizes its slices interactively using `ImageVisualizer`. The grid is defined by its size, spacing, and grid spacing. ```python grid = create_grid_image( size=(100, 100, 100), spacing=(1.0, 1.0, 1.0), grid_spacing=8, ) viz = ImageVisualizer.from_image(grid) viz.view_slices() ``` -------------------------------- ### AutoPipeline Force Index Update Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/autopipeline.md Illustrates how to force AutoPipeline to re-index the input directory, which is useful when new files have been added. This ensures all data is recognized for processing. ```bash imgtools autopipeline \ --modalities CT,RTSTRUCT \ --update-crawl \ /path/to/dicoms/ \ /path/to/output/ ``` -------------------------------- ### Create Index Database for DICOM Files Source: https://context7.com/bhklab/med-imagetools/llms.txt This command creates an index database from DICOM files in a specified directory. The `--output` flag defines the directory for the index, and `--jobs` enables parallel processing for faster indexing of large datasets. ```bash # Create index database imgtools index /data/dicoms/ --output .imgtools/ --jobs 8 ``` -------------------------------- ### Visualize Multiple Images for Comparison Source: https://github.com/bhklab/med-imagetools/blob/main/devnotes/transform_notebooks/transforms.ipynb Compares various generated images (Sphere, Grid, X-Gradient, Radial, Cross, Rod-X, Rod-Z, Checkerboard, CT Image) by displaying their middle slices. It iterates through a dictionary of images and uses a helper function `display_slices` for visualization. Dependencies include image objects and a display function. ```python # Create a visualization with multiple images to compare images = { "Sphere": sphere, "Grid": grid, "X-Gradient": x_gradient, "Radial": radial_gradient, "Cross": cross, "Rod-X": x_rod, "Rod-Z": z_rod, # "Noisy Sphere": noisy_sphere, "Checkerboard": checkerboard, "CT Image": ct_image } # Display middle slice of each image for name, image in images.items(): print(f"\n{name}:") size = image.GetSize() middle_slice = size[2] // 2 img = sitk.GetArrayViewFromImage(image) display_slices(img, x_index=middle_slice, y_index=middle_slice, z_index=middle_slice) ``` -------------------------------- ### Index File Logging with add_to_index Method Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/Writers/BaseWriter.md Demonstrates how to use the `add_to_index` method within a writer's `save` method to log file details to an index CSV. It shows parameters for including all context variables, specifying the filepath column, replacing existing entries, and enabling schema evolution. ```python class YourWriter: def __init__(self, index_writer): self.index_writer = index_writer def resolve_path(self, **kwargs): # Placeholder for path resolution logic return "/path/to/your/file.ext" def save(self, content, **kwargs): output_path = self.resolve_path(**kwargs) # Write your content to the file... print(f"Writing content to {output_path}") # Record this file in the index, with optional parameters: self.index_writer.add_to_index( path=output_path, include_all_context=True, # Include all context variables filepath_column="path", # Column name for file paths replace_existing=False, # Do not replace existing entries merge_columns=True # Allow schema evolution ) return output_path # Example Usage (assuming IndexWriter is initialized elsewhere): # from med_imagetools.writers.index_writer import IndexWriter # index_writer = IndexWriter() # writer = YourWriter(index_writer) # writer.save("some content", context_var1="value1") ``` -------------------------------- ### ROIMatcher Configuration and Usage in Python Source: https://context7.com/bhklab/med-imagetools/llms.txt Configures and demonstrates the ROIMatcher for flexible pattern-based ROI name matching. It covers list-based and dictionary-based matching, different handling strategies (MERGE, KEEP_FIRST, SEPARATE), and matching against actual ROI names. ```python from imgtools.coretypes.masktypes import ( ROIMatcher, ROIMatchStrategy, ROIMatchFailurePolicy ) # Simple list-based matching (all patterns merged) simple_matcher = ROIMatcher( match_map=['GTV.*', 'Parotid.*', 'Cord'], handling_strategy=ROIMatchStrategy.MERGE, ) # Dictionary-based with named groups (recommended) structured_matcher = ROIMatcher( match_map={ 'tumor_primary': ['GTV.*[Pp]', 'Gross.*Primary', 'Primary.*Tumor'], 'tumor_nodes': ['GTV.*[Nn]', 'Node.*', 'Nodal.*GTV'], 'parotid_left': ['Left.*Parotid', 'Parotid.*L(?:eft)?$', 'L_Parotid'], 'parotid_right': ['Right.*Parotid', 'Parotid.*R(?:ight)?$', 'R_Parotid'], 'brainstem': ['^Brainstem$', 'Brain.*Stem'], 'cord': ['^SpinalCord$', '^Cord$', 'Spinal.*Cord'], }, handling_strategy=ROIMatchStrategy.SEPARATE, ignore_case=True, allow_multi_key_matches=False, on_missing_regex=ROIMatchFailurePolicy.WARN, ) # Match against actual ROI names from structure set roi_names_from_dicom = [ 'GTVp', 'GTVn_Left', 'GTVn_Right', 'Left Parotid', 'Right Parotid', 'Brainstem', 'SpinalCord' ] matches = structured_matcher.match_rois(roi_names_from_dicom) for key, matched_rois in matches: print(f"{key}: {matched_rois}") # Handling strategies comparison # MERGE: Combine all matching ROIs into single channel merge_matcher = ROIMatcher( match_map={'all_gtvs': ['GTV.*']}, handling_strategy=ROIMatchStrategy.MERGE, ) # KEEP_FIRST: Use only first matching ROI first_matcher = ROIMatcher( match_map={'gtv': ['GTV.*']}, handling_strategy=ROIMatchStrategy.KEEP_FIRST, ) # SEPARATE: Each matching ROI gets own channel separate_matcher = ROIMatcher( match_map={'gtv': ['GTV.*']}, handling_strategy=ROIMatchStrategy.SEPARATE, ) ``` -------------------------------- ### Create Z-axis Rod Image and Visualize Source: https://github.com/bhklab/med-imagetools/blob/main/devnotes/transform_notebooks/transforms.ipynb Generates a 3D image representing a z-axis rod with specified dimensions and radius. It then visualizes the rod using interactive slices. Dependencies include image generation functions and an ImageVisualizer. ```python z_rod = create_rod_image( size=(100, 100, 100), spacing=(1.0, 1.0, 1.0), axis="z", radius=5, ) viz = ImageVisualizer.from_image(z_rod) viz.view_slices() ``` -------------------------------- ### Create and Visualize X-axis Rod Image Source: https://github.com/bhklab/med-imagetools/blob/main/devnotes/transform_notebooks/transforms.ipynb Generates an X-axis rod phantom image using `create_rod_image` and visualizes its slices interactively. The rod is defined by its size, spacing, axis ('x'), and radius. ```python # X-axis rod x_rod = create_rod_image( size=(100, 100, 100), spacing=(1.0, 1.0, 1.0), axis="x", radius=5, ) viz = ImageVisualizer.from_image(x_rod) viz.view_slices() ``` -------------------------------- ### Initialize and Draw Network Graph Source: https://github.com/bhklab/med-imagetools/blob/main/docs/interlacer.html This JavaScript function `drawGraph` initializes global variables and renders a network graph using the `vis.js` library. It parses node data, likely from a Python backend, and configures the network options before drawing. ```javascript // initialize global variables. var edges; var nodes; var allNodes; var allEdges; var nodeColors; var originalNodes; var network; var container; var options, data; var filter = { item : '', property : '', value : [] }; // This method is responsible for drawing the graph, returns the drawn network function drawGraph() { var container = document.getElementById('mynetwork'); // parsing and collecting nodes and edges from the python nodes = new vis.DataSet([ {"color": "#ff7f0e", "id": "1.3.6.1.4.1.14519.5.2.1.5168.1900.232182644086451239142307988600", "label": "MR", "shape": "dot", "title": "PatientID: STS\_001\nSeries: 1.3.6.1.4.1.14519.5.2.1.5168.1900.232182644086451239142307988600"}, {"color": "#9467bd", "id": "1.3.6.1.4.1.14519.5.2.1.5168.1900.147597676388012046340025692485", "label": "RTSTRUCT", "shape": "dot", "title": "PatientID: STS\_001\nSeries: 1.3.6.1.4.1.14519.5.2.1.5168.1900.147597676388012046340025692485"}, {"color": "#1f77b4", "id": "1.3.6.1.4.1.14519.5.2.1.5168.1900.293609116849698550139986038601", "label": "CT", "shape": "dot", "title": "PatientID: STS\_001\nSeries: 1.3.6.1.4.1.14519.5.2.1.5168.1900.293609116849698550139986038601"}, {"color": "#2ca02c", "id": "1.3.6.1.4.1.14519.5.2.1.5168.1900.279539551699081894888330051583", "label": "PT", "shape": "dot", "title": "PatientID: STS\_001\nSeries: 1.3.6.1.4.1.14519.5.2.1.5168.1900.279539551699081894888330051583"}, {"color": "#9467bd", "id": "1.3.6.1.4.1.14519.5.2.1.5168.1900.262680089418667859560984717357", "label": "RTSTRUCT", "shape": "dot", "title": "PatientID: STS\_001\nSeries: 1.3.6.1.4.1.14519.5.2.1.5168.1900.262680089418667859560984717357"}, {"color": "#9467bd", "id": "1.3.6.1.4.1.14519.5.2.1.5168.1900.294304652189082068687304577278", "label": "RTSTRUCT", "shape": "dot", "title": "PatientID: STS\_001\nSeries: 1.3.6.1.4.1.14519.5.2.1.5168.1900.294304652189082068687304577278"}, {"color": "#ff7f0e", "id": "1.3.6.1.4.1.14519.5.2.1.5168.1900.236909650266075940866375712555", "label": "MR", "shape": "dot", "title": "PatientID: STS\_001\nSeries: 1.3.6.1.4.1.14519.5.2.1.5168.1900.236909650266075940866375712555"}, {"color": "#9467bd", "id": "1.3.6.1.4.1.14519.5.2.1.5168.1900.169505605471360697610771464320", "label": "RTSTRUCT", "shape": "dot", "title": "PatientID: STS\_001\nSeries: 1.3.6.1.4.1.14519.5.2.1.5168.1900.169505605471360697610771464320"}, {"color": "#ff7f0e", "id": "1.3.6.1.4.1.14519.5.2.1.5168.1900.267475167888884755506702762438", "label": "MR", "shape": "dot", "title": "PatientID: STS\_001\nSeries: 1.3.6.1.4.1.14519.5.2.1.5168.1900.267475167888884755506702762438"}, {"color": "#9467bd", "id": "1.3.6.1.4." ]); } ``` -------------------------------- ### Autopipeline with ROI Matching from YAML File Source: https://context7.com/bhklab/med-imagetools/llms.txt This command utilizes a YAML file (`roi_config.yaml`) to define ROI matching rules. This is useful for managing complex or numerous ROI mappings. The `--roi-strategy merge` suggests that mapped ROIs might be combined. ```bash # With ROI matching from YAML file # roi_config.yaml: # GTV: ["GTV.*", "Gross.*Tumor"] # Parotid_L: ["Left.*Parotid", "Parotid.*L"] # Parotid_R: ["Right.*Parotid", "Parotid.*R"] imgtools autopipeline \ --modalities CT,RTSTRUCT \ --roi-match-yaml roi_config.yaml \ --roi-strategy merge \ /data/raw_dicoms/ \ /data/processed/ ``` -------------------------------- ### AutoPipeline ROI Standardization via CLI Source: https://github.com/bhklab/med-imagetools/blob/main/docs/usage/autopipeline.md Details how to standardize region of interest (ROI) names using the command-line interface with the `-rmap` option. This allows for flexible mapping of inconsistent ROI names to standardized ones. ```bash imgtools autopipeline\ --modalities CT,RTSTRUCT \ -rmap "GTV:GTV,gtv,Gross.*Volume" \ -rmap "Parotid_L:LeftParotid,PAROTID_L,L_Parotid" \ -rmap "Parotid_R:RightParotid,PAROTID_R,R_Parotid" \ -rmap "Cord:SpinalCord,Cord,Spinal_Cord" \ -rmap "Mandible:mandible.*" \ /path/to/dicoms/ \ /path/to/output/ ``` -------------------------------- ### Create and Visualize Sphere Image Source: https://github.com/bhklab/med-imagetools/blob/main/devnotes/transform_notebooks/transforms.ipynb Generates a spherical phantom image using `create_sphere_image` and visualizes its slices interactively using `ImageVisualizer`. The image is defined by its size, spacing, and radius. ```python sphere = create_sphere_image( size=(100, 100, 100), spacing=(1.0, 1.0, 1.0), radius=20, ) viz = ImageVisualizer.from_image(sphere) viz.view_slices() ``` -------------------------------- ### Build Relationship Graph from Index Source: https://context7.com/bhklab/med-imagetools/llms.txt This command uses the generated index file (`.imgtools/index.csv`) to build a relationship graph between different modalities (e.g., CT and RTSTRUCT) using the `--query` option. This helps in understanding how different scans relate to each other for a given patient. ```bash # Build relationship graph imgtools interlacer .imgtools/index.csv --query CT,RTSTRUCT ```