### Install Kimimaro with Optional Dependencies Source: https://github.com/seung-lab/kimimaro/blob/master/README.md Install Kimimaro with specific optional dependencies for acceleration, viewing, TIFF generation, or all formats. Use `[all]` to install all optional dependencies. ```bash pip install kimimaro # installs additional libraries to accelerate some # operations like join_close_components pip install "kimimaro[accel]" # Makes the kimimaro view command work pip install "kimimaro[view]" # Enables TIFF generation on the CLI pip install "kimimaro[tif]" # Enables reading NIBABEL, NRRD, TIFF, CRACKLE on the CLI pip install "kimimaro[all_formats]" # Install all optional dependencies pip install "kimimaro[all]" ``` -------------------------------- ### Install Kimimaro with Optional Features Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/README.md Install the Kimimaro library using pip. Optional features like acceleration, visualization, or all features can be included in the installation command. ```bash pip install kimimaro # With optional acceleration pip install "kimimaro[accel]" # With visualization support pip install "kimimaro[view]" # All optional features pip install "kimimaro[all]" ``` -------------------------------- ### Install Kimimaro with Acceleration Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/join_close_components.md Install Kimimaro with optional acceleration packages, including pykdtree for faster spatial queries. ```bash pip install "kimimaro[accel]" ``` -------------------------------- ### Install Visualization Dependencies Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/configuration.md Installs the optional dependencies required for the visualization features of Kimimaro, including the interactive viewer and VTK. ```bash pip install "kimimaro[view]" ``` -------------------------------- ### Install C++ Compiler for Kimimaro Source: https://github.com/seung-lab/kimimaro/blob/master/README.md Install necessary development headers and a C++ compiler on Ubuntu Linux if a binary is not available for your platform. ```bash sudo apt-get install python3-dev g++ # ubuntu linux ``` -------------------------------- ### Install Kimimaro Optional Dependencies Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/configuration.md Install Kimimaro with specific feature sets using pip. Choose minimal dependencies, acceleration, visualization, multiple file format support, or all features. ```bash # Just skeletonization (minimal dependencies) pip install kimimaro # Add acceleration (kdtree, faster joins) pip install "kimimaro[accel]" # Add visualization pip install "kimimaro[view]" # Add multiple file format support pip install "kimimaro[all_formats]" # Add everything pip install "kimimaro[all]" ``` -------------------------------- ### Skeleton I/O Operations Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/utility_functions.md Examples for exporting a Skeleton object to SWC format and creating an independent copy. ```python # I/O skel.to_swc(filename) # Export to SWC format skel.clone() # Create independent copy ``` -------------------------------- ### Postprocessing Workflow with Joining Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/join_close_components.md Demonstrates a complete workflow involving skeletonization, joining of components across multiple chunks, and postprocessing to clean up the final skeleton. This example shows how `join_close_components` fits into a larger data processing pipeline. ```python import kimimaro # Complete workflow for merging chunks chunks = load_chunks() # List of labeled volume chunks # Skeletonize each chunk chunk_skels = {} for chunk_id, chunk_labels in chunks.items(): chunk_skels[chunk_id] = kimimaro.skeletonize( chunk_labels, anisotropy=(4, 4, 40), ) # Merge all chunk skeletons per original label merged_by_label = {} for label_id in get_all_label_ids(): label_chunk_skels = [ chunk_skels[cid].get(label_id) for cid in chunks.keys() if label_id in chunk_skels[cid] ] if label_chunk_skels: # Join components from different chunks merged = kimimaro.join_close_components( label_chunk_skels, radius=3000.0, # Limit joining distance ) merged_by_label[label_id] = merged # Postprocess final_skels = {} for label_id, skel in merged_by_label.items(): cleaned = kimimaro.postprocess( skel, dust_threshold=1500.0, tick_threshold=3000.0, ) if not cleaned.empty(): final_skels[label_id] = cleaned ``` -------------------------------- ### Interactive Point Selection for Path Extraction Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/connect_points.md Demonstrates extracting a path using predetermined start and end points, simulating an interactive selection process. The extracted skeleton is then exported to SWC format. ```python import kimimaro import numpy as np # Load volume and display for interactive point selection volume = np.load("segmentation.npy") target_label = 12345 # Use external tool to identify start/end points (pseudocode) # points = interactive_viewer.select_points(volume, target_label) # start, end = points[0], points[1] # For this example, use predetermined points start = (150, 200, 75) end = (300, 250, 150) # Extract path binary = (volume == target_label) skeleton = kimimaro.connect_points( binary, start=start, end=end, anisotropy=(4, 4, 40), ) # Export skeleton.to_swc("manual_path.swc") ``` -------------------------------- ### Merge Skeletons Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/utility_functions.md Example of merging multiple skeletons using the static simple_merge method. ```python # Merging Skeleton.simple_merge([s1, s2]) # Merge multiple skeletons ``` -------------------------------- ### Customizing TEASAR Parameters for Skeletonization Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/skeletonize.md Customize skeletonization parameters, such as 'scale' and 'const', to fine-tune the process for specific structures like neurons with smaller spines. This example also demonstrates setting anisotropy and enabling progress reporting. ```python import kimimaro labels = np.load("segmentation.npy") # Customize skeletonization for neurons with smaller spines skeletons = kimimaro.skeletonize( labels, teasar_params={ "scale": 2.0, # Larger invalidation radius per spine size "const": 500, # Larger additive radius "pdrf_scale": 100000, "pdrf_exponent": 4, "soma_acceptance_threshold": 5000, # Larger soma detection "soma_detection_threshold": 1000, "soma_invalidation_scale": 2.5, "soma_invalidation_const": 300, }, anisotropy=(4, 4, 40), # 4nm x 4nm x 40nm voxels progress=True, ) ``` -------------------------------- ### Query Skeleton Structure Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/utility_functions.md Examples of querying the structure of a Skeleton object, including cable length, emptiness check, consolidation, connected components, and path retrieval. ```python # Query structure skel.cable_length() # Sum of all edge lengths skel.empty() # Check if skeleton has vertices skel.consolidate() # Clean up graph (remove disconnected vertices) skel.components() # Get list of connected components skel.paths() # Get all paths between terminals ``` -------------------------------- ### Create and Use Bbox from Slices Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/utility_functions.md Demonstrates how to create a Bbox object from slices and access its properties like minpt, maxpt, and size. Also shows how to calculate volume and perform operations like growing the bbox or converting it back to slices. ```python from osteoid import Bbox, Vec # Create from slices bbox = Bbox.from_slices((slice(10, 100), slice(20, 150), slice(5, 85))) # Properties minpt = bbox.minpt # Vector of minimum coordinates maxpt = bbox.maxpt # Vector of maximum coordinates size = bbox.size # Vector of dimensions volume = bbox.volume() # Integer count of voxels # Operationsbox.grow(distance) # Expand in all directionsbox.to_slices() # Convert to tuple of slices ``` -------------------------------- ### Kimimaro CLI Help Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/configuration.md Displays the help message for the Kimimaro CLI, showing available commands and options. ```bash kimimaro --help ``` -------------------------------- ### Handle DimensionError in skeletonize Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/utility_functions.md Example of catching DimensionError when calling kimimaro.skeletonize with an invalid input shape. ```python import kimimaro try: result = kimimaro.skeletonize(4d_array) except kimimaro.DimensionError as e: print(f"Invalid input shape: {e}") ``` -------------------------------- ### Extract Neurite Branch Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/connect_points.md Shows how to extract a specific neurite branch by providing start and end points on the desired structure within a segmentation. ```APIDOC ## connect_points with specific branch extraction ### Description Extracts a single neurite branch by connecting specified start and end points. ### Parameters #### Path Parameters - **binary** (numpy.ndarray) - Required - Binary mask of the neuron. - **start_point** (tuple) - Required - Starting coordinates on the neurite. - **end_point** (tuple) - Required - Ending coordinates on the neurite. - **anisotropy** (tuple, optional) - Default: (1, 1, 1) - Anisotropy factor for the image dimensions. ### Returns - **dendrite** (kimimaro.Skeleton) - The skeleton representing the neurite branch. ### Usage Example ```python import kimimaro # Load labeled volume and extract binary mask for specific neuron labels = np.load("segmentation.npy") neuron_id = 12345 binary = (labels == neuron_id) # Manually select two points on the dendrite or axon start_point = (150, 200, 75) end_point = (300, 250, 150) # Extract centerline dendrite = kimimaro.connect_points( binary, start=start_point, end=end_point, anisotropy=(4, 4, 40), ) # Export for visualization dendrite.to_swc("dendrite_branch.swc") ``` ``` -------------------------------- ### Basic Skeletonization Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/configuration.md Performs skeletonization with essential parameters for scale, constant, and progress display. ```bash kimimaro forge segmentation.npy \ --scale 1.5 \ --const 300 \ --progress ``` -------------------------------- ### Kimimaro Command Structure Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/configuration.md Illustrates the hierarchical structure of Kimimaro commands, including entry points for skeletonization, conversion, and visualization. ```bash kimimaro ├── forge Skeletonize an input image volume ├── swc Convert between binary images and SWC skeletons └── view Visualize SWC files or image volumes ``` -------------------------------- ### Visualize Cross-Section Planes Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/cross_sectional_area.md Enable visualization of cross-section planes during analysis. This feature requires the microviewer to be installed and opens an interactive window to inspect the calculated planes. ```python import kimimaro labels = np.load("segmentation.npy") skeletons = kimimaro.skeletonize(labels) # Visualize cross-section planes (requires microviewer) skeletons = kimimaro.cross_sectional_area( labels, skeletons, anisotropy=(4, 4, 40), visualize_section_planes=True, # Opens microviewer window smoothing_window=5, ) ``` -------------------------------- ### Produce SWC files and view skeletons Source: https://github.com/seung-lab/kimimaro/blob/master/README.md Use the 'forge' command to produce SWC files from volumetric images and the 'view' command to visualize the generated skeletons. ```bash kimimaro forge labels.npy --progress # writes to ./kimimaro_out/ kimimaro view kimimaro_out/10.swc ``` -------------------------------- ### Example of Triggering DimensionError Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/errors.md Demonstrates how DimensionError is raised when `kimimaro.skeletonize()` receives an input array with more than three non-trivial dimensions. Includes valid 2D and 3D cases for comparison. ```python import kimimaro import numpy as np # Valid: 2D array (padded to 3D) labels_2d = np.zeros((512, 512), dtype=np.uint32) result = kimimaro.skeletonize(labels_2d) # OK # Valid: 3D array labels_3d = np.zeros((512, 512, 256), dtype=np.uint32) result = kimimaro.skeletonize(labels_3d) # OK # Invalid: 4D array labels_4d = np.zeros((512, 512, 256, 10), dtype=np.uint32) try: result = kimimaro.skeletonize(labels_4d) except kimimaro.DimensionError as e: print(f"Error: {e}") # Output: Input labels may be no more than three non-trivial dimensions. Got: (512, 512, 256, 10) ``` -------------------------------- ### Skeletonize with Custom TEASAR Parameters Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/types.md Demonstrates how to use the `skeletonize` function with custom TEASAR parameters for fine-tuning the skeletonization process. This allows overriding default values for various parameters. ```python import kimimaro # Use defaults skels = kimimaro.skeletonize(labels) # Custom parameters skels = kimimaro.skeletonize( labels, teasar_params={ "scale": 2.0, "const": 500, "pdrf_scale": 50000, "pdrf_exponent": 2, "soma_acceptance_threshold": 5000, "soma_detection_threshold": 1000, "soma_invalidation_scale": 2.5, "soma_invalidation_const": 400, "max_paths": 500, } ) ``` -------------------------------- ### Configure Skeletonization with TEASAR Parameters Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/configuration.md Demonstrates how to configure the skeletonization process in the Kimimaro Python API using function parameters, including TEASAR specific settings. ```python import kimimaro # Configure skeletonization skels = kimimaro.skeletonize( labels, # TEASAR parameters (all in physical units) teasar_params={ "scale": 1.5, "const": 300, "pdrf_scale": 100000, "pdrf_exponent": 4, "soma_acceptance_threshold": 3500, "soma_detection_threshold": 750, "soma_invalidation_scale": 2, "soma_invalidation_const": 300, }, # Preprocessing anisotropy=(4, 4, 40), dust_threshold=1000, fill_holes=False, fix_avocados=False, # Algorithm options fix_branching=True, fix_borders=True, # Performance parallel=-1, # Use all CPUs parallel_chunk_size=100, # I/O progress=True, in_place=False, ) ``` -------------------------------- ### Draw Centerline Between Points Source: https://github.com/seung-lab/kimimaro/blob/master/README.md Create a skeleton by drawing a centerline between specified start and end points within a binary image. This is useful for simpler, targeted skeletonization tasks. ```python skel = kimimaro.connect_points( labels == 67301298, start=(3, 215, 202), end=(121, 426, 227), anisotropy=(32,32,40), ) ``` -------------------------------- ### Convert Binary Image Skeletons to SWC using CLI Source: https://github.com/seung-lab/kimimaro/blob/master/README.md Convert binary image skeletons to SWC format. This is useful for comparing different skeletonization algorithms. ```bash kimimaro swc from binary_image.tiff # -> binary_image.swc ``` -------------------------------- ### Print Default TEASAR Parameters Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/configuration.md Retrieves and prints the default TEASAR parameters used by the Kimimaro Python API. These parameters can be used as a reference or starting point for custom configurations. ```python from kimimaro.intake import DEFAULT_TEASAR_PARAMS print(DEFAULT_TEASAR_PARAMS) # { # 'scale': 1.5, # 'const': 300, # 'pdrf_scale': 100000, # 'pdrf_exponent': 4, # 'soma_acceptance_threshold': 3500, # 'soma_detection_threshold': 750, # 'soma_invalidation_const': 300, # 'soma_invalidation_scale': 2 # } ``` -------------------------------- ### Skeletonize Labeled Image with Kimimaro Source: https://github.com/seung-lab/kimimaro/blob/master/README.md Use this function to produce skeletons from a labeled image volume. Ensure you have the 'crackle-codec' installed for loading data. Adjust 'teasar_params' for specific segmentation characteristics. ```python import kimimaro import crackle labels = crackle.load("benchmarks/connectomics.npy.ckl.gz") skels = kimimaro.skeletonize( labels, teasar_params={ "scale": 1.5, "const": 300, # physical units "pdrf_scale": 100000, "pdrf_exponent": 4, "soma_acceptance_threshold": 3500, # physical units "soma_detection_threshold": 750, # physical units "soma_invalidation_const": 300, # physical units "soma_invalidation_scale": 2, "max_paths": 300, # default None }, # object_ids=[ ... ], # process only the specified labels # extra_targets_before=[ (27,33,100), (44,45,46) ], # target points in voxels # extra_targets_after=[ (27,33,100), (44,45,46) ], # target points in voxels dust_threshold=1000, # skip connected components with fewer than this many voxels anisotropy=(16,16,40), # default True fix_branching=True, # default True fix_borders=True, # default True fill_holes=False, # default False fix_avocados=False, # default False progress=True, # default False, show progress bar parallel=1, # <= 0 all cpu, 1 single process, 2+ multiprocess parallel_chunk_size=100, # how many skeletons to process before updating progress bar ) ``` -------------------------------- ### Connect Points in Kimimaro Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/errors.md Demonstrates the usage of kimimaro.connect_points() with different point configurations. Includes cases for points in the same component, different components, and points in the background, highlighting expected outcomes and error handling. ```python import kimimaro import numpy as np binary_image = np.zeros((100, 100, 100), dtype=np.uint8) binary_image[10:50, 10:50, 10:50] = 1 # Component 1 binary_image[60:80, 60:80, 60:80] = 1 # Component 2 (separate) # Points in same component: OK try: skel = kimimaro.connect_points( binary_image, start=(20, 20, 20), # In component 1 end=(40, 40, 40), # In component 1 ) print("Success: extracted path") except ValueError as e: print(f"Error: {e}") # Points in different components: ERROR try: skel = kimimaro.connect_points( binary_image, start=(20, 20, 20), # In component 1 end=(70, 70, 70), # In component 2 ) except ValueError as e: print(f"Error: {e}") # Output: Cannot extract centerline from disconnected components. # Point in background: ERROR try: skel = kimimaro.connect_points( binary_image, start=(5, 5, 5), # In background end=(40, 40, 40), # In component 1 ) except ValueError as e: print(f"Error: {e}") ``` -------------------------------- ### Visualize SWC Skeleton Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/configuration.md Opens an interactive 3D viewer for an SWC skeleton file. ```bash kimimaro view ``` -------------------------------- ### Boundary Behavior in connect_points() Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/errors.md The connect_points() function does not raise errors for degenerate cases, such as identical start and end points or when start/end points lie on the image boundary. It returns a valid skeleton even in these scenarios. ```python import kimimaro binary = np.ones((100, 100, 100), dtype=np.uint8) # Identical start and end points skel = kimimaro.connect_points(binary, start=(50, 50, 50), end=(50, 50, 50)) # Returns: skeleton with 1 vertex and 0 edges # Start/end on boundary skel = kimimaro.connect_points( binary, start=(0, 0, 0), # On image boundary end=(99, 99, 99), # On opposite boundary ) # Returns: valid skeleton (no error) ``` -------------------------------- ### Skeletonize Labeled Volumes (CLI) Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/INDEX.md Use the command line interface to skeletonize labeled volumes. Adjust scale and connectivity parameters as needed. ```bash kimimaro forge segmentation.npy --scale 1.5 --const 300 --progress ``` -------------------------------- ### Basic Point-to-Point Connection Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/connect_points.md Demonstrates the fundamental usage of connect_points to draw a path between two specified coordinates in a binary image. ```APIDOC ## connect_points ### Description Draws a path between two points in a binary image. ### Parameters #### Path Parameters - **binary_image** (numpy.ndarray) - Required - The input 3D binary image. - **start** (tuple) - Required - The starting coordinates (x, y, z). - **end** (tuple) - Required - The ending coordinates (x, y, z). - **anisotropy** (tuple, optional) - Default: (1, 1, 1) - Anisotropy factor for the image dimensions. - **fill_holes** (bool, optional) - Default: False - Whether to fill holes in the binary image before pathfinding. - **pdrf_scale** (float, optional) - Controls the emphasis on centeredness. - **pdrf_exponent** (float, optional) - Controls the emphasis on centeredness. ### Returns - **skeleton** (kimimaro.Skeleton) - The generated skeleton object. ### Throws - **ValueError** - If start and end points are in different connected components or one is in the background. ``` -------------------------------- ### Convert Synapse Detections to Skeleton Targets Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/utility_functions.md Use this function to convert detected synapse coordinates and their types into a dictionary of target voxel coordinates and SWC labels. This is useful for guiding the skeletonization process. Ensure you have the `kimimaro` library imported and the `labels` numpy array loaded. ```python import kimimaro labels = np.load("segmentation.npy") # Detected synapses: label -> list of (centroid, swc_type) synapses = { 100: [((50.5, 100.2, 75.3), 5), ((80.1, 120.5, 85.2), 6)], 200: [((150.3, 200.1, 100.4), 5)], } # Convert to targets targets = kimimaro.synapses_to_targets(labels, synapses, progress=True) # Use in skeletonization skeletons = kimimaro.skeletonize( labels, extra_targets_after=[tuple(t) for t in targets.keys()]), ) ``` -------------------------------- ### Skeletonize Volumetric Data with Kimimaro CLI Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/README.md Utilize the Kimimaro command-line interface (CLI) to skeletonize volumetric data. Supports default parameters, custom TEASAR parameters, and anisotropy settings. ```bash # Skeletonize with default parameters kimimaro forge segmentation.npy --progress # Custom TEASAR parameters kimimaro forge data.npy \ --scale 1.5 \ --const 300 \ --anisotropy 4,4,40 \ --progress ``` -------------------------------- ### Visualize Skeleton or Segmentation using CLI Source: https://github.com/seung-lab/kimimaro/blob/master/README.md The 'view' command allows visualization of generated SWC files or segmentation data (npy). ```bash kimimaro view 1241241.swc # visualize skeleton ``` ```bash kimimaro view labels.npy # visualize segmentation ``` -------------------------------- ### Basic Skeletonization with kimimaro Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/skeletonize.md Skeletonize all non-zero labels in a volume using default TEASAR parameters. This is the most straightforward way to obtain skeleton data. ```python import kimimaro import numpy as np # Load a labeled volume (e.g., from segmentation) labels = np.load("segmentation.npy") # Skeletonize all non-zero labels with default parameters skeletons = kimimaro.skeletonize(labels) # Iterate over results for label_id, skeleton in skeletons.items(): print(f"Label {label_id}: {skeleton.vertices.shape[0]} vertices") ``` -------------------------------- ### View Skeleton Data with Kimimaro CLI Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/README.md Use the Kimimaro CLI to visualize skeleton data from an SWC file. This command opens an interactive viewer for the specified skeleton file. ```bash kimimaro view neuron_12345.swc ``` -------------------------------- ### Comparing Pathfinding Parameters Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/connect_points.md Compares the results of pathfinding with different `pdrf_scale` and `pdrf_exponent` parameters. A higher `pdrf_scale` and `pdrf_exponent` lead to more conservative, centered paths, while lower values result in more aggressive, shorter paths. ```python import kimimaro binary_img = load_binary_image() # Conservative pathfinding (more centered) conservative = kimimaro.connect_points( binary_img, start=(20, 20, 20), end=(80, 80, 80), pdrf_scale=200000, # Higher emphasis on centeredness pdrf_exponent=8, ) # Aggressive pathfinding (shorter paths) aggressive = kimimaro.connect_points( binary_img, start=(20, 20, 20), end=(80, 80, 80), pdrf_scale=50000, # Lower emphasis pdrf_exponent=2, ) print(f"Conservative length: {conservative.cable_length():.2f}") print(f"Aggressive length: {aggressive.cable_length():.2f}") ``` -------------------------------- ### Visualize Volume Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/configuration.md Opens a volume in the 3D viewer for inspection before skeletonization. ```bash kimimaro view ``` -------------------------------- ### Advanced Skeletonization Parameters Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/configuration.md Utilizes advanced parameters for tuning skeletonization, suitable for glia or large somata, including hole filling and path limits. ```bash kimimaro forge glia_segmentation.npy \ --scale 2.0 \ --const 500 \ --pdrf-scale 50000 \ --pdrf-exponent 4 \ --soma-detect 1000 \ --soma-accept 5000 \ --soma-scale 2.5 \ --soma-const 400 \ --fix-holes \ --max-paths 300 \ --parallel -1 \ --progress ``` -------------------------------- ### Comparing Pathfinding Parameters Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/connect_points.md Illustrates how adjusting `pdrf_scale` and `pdrf_exponent` can influence the pathfinding behavior, leading to more conservative or aggressive paths. ```APIDOC ## connect_points with pathfinding parameter comparison ### Description Compares the results of `connect_points` using different `pdrf_scale` and `pdrf_exponent` values to influence pathfinding. ### Parameters #### Path Parameters - **binary_img** (numpy.ndarray) - Required - The input binary image. - **start** (tuple) - Required - The starting coordinates. - **end** (tuple) - Required - The ending coordinates. - **pdrf_scale** (float, optional) - Controls the emphasis on centeredness. Lower values lead to shorter paths. - **pdrf_exponent** (float, optional) - Controls the emphasis on centeredness. Lower values lead to shorter paths. ### Usage Example ```python import kimimaro binary_img = load_binary_image() # Assume this function is defined # Conservative pathfinding (more centered) conservative = kimimaro.connect_points( binary_img, start=(20, 20, 20), end=(80, 80, 80), pdrf_scale=200000, # Higher emphasis on centeredness pdrf_exponent=8, ) # Aggressive pathfinding (shorter paths) aggressive = kimimaro.connect_points( binary_img, start=(20, 20, 20), end=(80, 80, 80), pdrf_scale=50000, # Lower emphasis pdrf_exponent=2, ) print(f"Conservative length: {conservative.cable_length():.2f}") print(f"Aggressive length: {aggressive.cable_length():.2f}") ``` ``` -------------------------------- ### Robust Skeletonization with Error Handling (Python) Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/errors.md This snippet demonstrates how to skeletonize labels using Kimimaro with comprehensive error handling. It includes specific catches for DimensionError and MemoryError, with strategies to mitigate MemoryError by adjusting parallel processing. It also includes a general exception catch for unexpected errors. ```python import kimimaro import logging logger = logging.getLogger(__name__) def robust_skeletonize(labels, **kwargs): """Skeletonize with comprehensive error handling.""" try: # Validate input if labels is None or labels.size == 0: logger.warning("Empty input labels") return {} # Perform skeletonization return kimimaro.skeletonize(labels, **kwargs) except kimimaro.DimensionError as e: logger.error(f"Dimension error: {e}") # Attempt to reshape or downgrade dimensionality raise except MemoryError as e: logger.error(f"Out of memory: {e}") # Try with reduced parallel processes or smaller chunks kwargs['parallel'] = 1 kwargs['parallel_chunk_size'] = 10 return kimimaro.skeletonize(labels, **kwargs) except Exception as e: logger.exception(f"Unexpected error: {e}") raise ``` -------------------------------- ### Handle Empty Input with skeletonize() Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/errors.md When skeletonize encounters input with no labels or only background, it returns an empty dictionary. This applies to both completely empty volumes and volumes containing only background voxels. ```python import kimimaro import numpy as np # Empty volume empty_labels = np.zeros((100, 100, 100), dtype=np.uint32) result = kimimaro.skeletonize(empty_labels) # Returns: {} (empty dict) # Only background background_only = np.zeros((100, 100, 100), dtype=np.uint32) result = kimimaro.skeletonize(background_only) # Returns: {} (empty dict) ``` -------------------------------- ### Parallel Skeletonization Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/configuration.md Enables parallel processing using all available CPU cores for faster skeletonization and specifies an output directory. ```bash kimimaro forge labels.npy \ --parallel 0 \ --progress \ -o ./results/ ``` -------------------------------- ### Basic Point-to-Point Connection Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/connect_points.md Connects two specified points in a binary image to generate a skeleton. Useful for basic path extraction where anisotropy is known. ```python import kimimaro import numpy as np # Create or load a binary segmentation binary_image = np.zeros((100, 100, 100), dtype=np.uint8) # ... populate with segmentation ... # Draw path from (10, 10, 10) to (80, 80, 80) skeleton = kimimaro.connect_points( binary_image, start=(10, 10, 10), end=(80, 80, 80), anisotropy=(4, 4, 40), ) print(f"Skeleton vertices: {skeleton.vertices.shape[0]}") print(f"Skeleton edges: {skeleton.edges.shape[0]}") print(f"Cable length: {skeleton.cable_length():.2f} nm") ``` -------------------------------- ### Generate SWC from Image using CLI Source: https://github.com/seung-lab/kimimaro/blob/master/README.md Use the 'forge' command to generate SWC files from a label image (npy). Adjust parameters like scale, const, soma detection, and anisotropy for optimal results. The output is written to ./kimimaro_out/$LABEL.swc by default. ```bash kimimaro forge labels.npy --scale 4 --const 10 --soma-detect 1100 --soma-accept 3500 --soma-scale 1 --soma-const 300 --anisotropy 16,16,40 --fix-borders --progress ``` -------------------------------- ### Basic Skeletonization Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/skeletonize.md Skeletonizes all non-zero labels in a given volume using default parameters. ```APIDOC ## kimimaro.skeletonize ### Description Skeletonizes all non-zero labels in a labeled volume using default parameters. ### Method `kimimaro.skeletonize(labels, **kwargs)` ### Parameters * **labels** (numpy.ndarray) - A labeled volume where non-zero values represent objects to be skeletonized. * **teasar_params** (dict, optional) - Dictionary of parameters for the TEASAR algorithm. Defaults to a predefined set. * **object_ids** (list[int], optional) - A list of specific object IDs to skeletonize. If None, all non-zero labels are processed. * **anisotropy** (tuple[float, float, float], optional) - Voxel dimensions in physical units (e.g., nm). Defaults to (1.0, 1.0, 1.0). * **progress** (bool, optional) - Whether to display a progress bar. Defaults to False. * **parallel** (int, optional) - Number of parallel processes to use. -1 uses all available CPUs. Defaults to 1. * **parallel_chunk_size** (int, optional) - Number of skeletons to process per parallel task. Defaults to 100. * **fix_borders** (bool, optional) - Whether to apply border fixing algorithms. Defaults to False. ### Return Value `dict[int, osteoid.Skeleton]` — Dictionary mapping original label IDs to their corresponding Skeleton objects. Each skeleton contains vertices and edges describing the skeletonized structure. ### Throws * **DimensionError** - Input array has more than 3 non-trivial dimensions. ### Usage Example ```python import kimimaro import numpy as np # Load a labeled volume (e.g., from segmentation) labels = np.load("segmentation.npy") # Skeletonize all non-zero labels with default parameters skeletons = kimimaro.skeletonize(labels) # Iterate over results for label_id, skeleton in skeletons.items(): print(f"Label {label_id}: {skeleton.vertices.shape[0]} vertices") ``` ``` -------------------------------- ### Handle Volume Below Dust Threshold with skeletonize() Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/errors.md If the total volume of a component is below the specified dust_threshold, skeletonize() will return an empty dictionary. This is demonstrated when the threshold is set higher than the total number of voxels in the input. ```python import kimimaro labels = np.ones((50, 50, 50), dtype=np.uint32) # Total volume (50*50*50 = 125,000) but dust threshold is high result = kimimaro.skeletonize( labels, dust_threshold=1000000, # Threshold > total size ) # Returns: {} (empty dict) because single component is below threshold ``` -------------------------------- ### Interactive Point Selection for Path Extraction Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/api-reference/connect_points.md Illustrates a workflow where points are interactively selected (conceptually) and then used with `connect_points` to extract a path. ```APIDOC ## connect_points with interactive point selection workflow ### Description Describes a workflow where start and end points are identified interactively (e.g., using a viewer) and then passed to `connect_points` for path extraction. ### Parameters #### Path Parameters - **binary** (numpy.ndarray) - Required - The binary image of the structure. - **start** (tuple) - Required - The interactively selected starting coordinates. - **end** (tuple) - Required - The interactively selected ending coordinates. - **anisotropy** (tuple, optional) - Default: (1, 1, 1) - Anisotropy factor for the image dimensions. ### Usage Example ```python import kimimaro import numpy as np # Load volume and display for interactive point selection volume = np.load("segmentation.npy") # Assume this function is defined target_label = 12345 # Use external tool to identify start/end points (pseudocode) # points = interactive_viewer.select_points(volume, target_label) # Assume interactive_viewer is available # start, end = points[0], points[1] # For this example, use predetermined points start = (150, 200, 75) end = (300, 250, 150) # Extract path binary = (volume == target_label) skeleton = kimimaro.connect_points( binary, start=start, end=end, anisotropy=(4, 4, 40), ) # Export skeleton.to_swc("manual_path.swc") ``` ``` -------------------------------- ### Primary Skeletonization Cost Calculation Source: https://github.com/seung-lab/kimimaro/wiki/The-Economics:-Skeletons-for-the-People This snippet outlines the cost calculation for the primary skeletonization phase of Kimimaro on a petavoxel dataset. It details the number of tasks, core hours, and estimated compute cost based on preemptible instance pricing. ```plaintext PRIMARY SKELETONIZATION 1 Petavoxel = 200,000 x 200,000 x 25,000 voxels at 4x4x40 nm resolution MIP 3 (typically 32x32x40 nm) = 25,000 x 25,000 x 25,000 voxels = 15.6 TVx Using 512x512x512 voxel tasks = 116,416 tasks Cloud computing using preemptible highmem instances ≈ $0.0135 per vCPU/hr Typical task time ≈ 30 min (based on large scale run in Jan. 2020, data dependent) Core Hours: (116,416 tasks) * (30 min / 60 min/hr) = 58,208 core-hours Compute Time Cost ≈ (58,208 core-hours) * (0.0135 $/core-hr) ≈ $786 ``` -------------------------------- ### Convert SWC to Binary Image Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/configuration.md Converts an SWC skeleton file to a binary image format. Specify the input SWC file and the desired output format. ```bash kimimaro swc to neuron.swc --format tiff ``` -------------------------------- ### Skeletonization with Custom Voxel Dimensions Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/configuration.md Configures skeletonization for data with specific voxel dimensions (e.g., EM data) and adjusts soma detection thresholds. ```bash kimimaro forge connectomics_data.npy \ --scale 1.5 \ --const 300 \ --anisotropy 4,4,40 \ --soma-detect 1100 \ --soma-accept 3500 \ --progress ``` -------------------------------- ### Default TEASAR Parameters Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/types.md Provides the default configuration for TEASAR parameters used by Kimimaro's skeletonization function when no custom parameters are specified. ```python kimimaro.intake.DEFAULT_TEASAR_PARAMS = { "scale": 1.5, "const": 300, "pdrf_scale": 100000, "pdrf_exponent": 4, "soma_acceptance_threshold": 3500, "soma_detection_threshold": 750, "soma_invalidation_const": 300, "soma_invalidation_scale": 2 } ``` -------------------------------- ### Proofreading Integration with Kimimaro Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/README.md Integrate Kimimaro with proofreading systems by first segmenting labels and then exporting them along with their skeletons. This is useful for systems that use atomic labels. ```python skels = kimimaro.skeletonize(labels) overseg_labels, overseg_skels = kimimaro.oversegment(labels, skels) # Export for proofreading system write_to_database(overseg_labels, overseg_skels) ``` -------------------------------- ### Utility Functions Source: https://github.com/seung-lab/kimimaro/blob/master/_autodocs/INDEX.md Helper functions and classes for skeleton extraction, analysis, and I/O operations. Includes core data structures and custom exception classes. ```APIDOC ## Utility Functions ### Description Provides essential helper functions and classes for various skeletonization tasks, including extraction, analysis, and data handling. ### Key Functions and Classes - `extract_skeleton_from_binary_image()`: Extracts topology from thinned binary images. - `oversegment()`: Generates atomic labels aligned with skeleton structures. - `synapses_to_targets()`: Converts synapse detections into target points. - `DimensionError`: Custom exception class for dimension-related errors. - `Skeleton` class: The core data structure for representing skeletons (from osteoid). - `osteoid.Bbox`: Helper class for defining regions of interest. ```