API Documentation
This section provides detailed documentation for the programmatic interface of the Napari Chromosome Analysis toolkit.
Core Classes
ImageProcessor
The main image processing class that handles segmentation, spot detection, and analysis.
- class image_processor.ImageProcessor[source]
Bases:
object- get_spots_in_common_regions(df_spots, common_nuclei)[source]
Filter spots to only include those in common regions.
Parameters:
- df_spotspandas.DataFrame
DataFrame containing spot coordinates with columns [‘Y’, ‘X’]
- common_nucleinumpy.ndarray
Label image of common regions
Returns:
- pandas.DataFrame
Filtered DataFrame containing only spots in common regions
- segment_image(image, save_dir=None)[source]
Segment the image using Cellpose and optionally save the results.
- Parameters:
image – Input image to segment
save_dir – Optional directory to save intermediate results
- Returns:
The segmented image masks
- ndi = <module 'scipy.ndimage' from '/home/docs/checkouts/readthedocs.org/user_builds/metachrome/envs/latest/lib/python3.9/site-packages/scipy/ndimage/__init__.py'>
- detect_spots_cent(image, channel_type, threshold, save_dir=None)[source]
Detect spots and save results if save_dir is provided.
- Parameters:
image – Input image
channel_type – Type of channel (‘DNA-FISH’ or ‘CENPC’)
threshold – Detection threshold
save_dir – Directory to save results (optional)
- Returns:
Array of centroids if spots are detected, None otherwise
- Return type:
- detect_spots_no_segmentation(image, threshold=0.4, channel=None)[source]
Detect spots in an image without segmentation.
- Parameters:
image – Input image
threshold – Detection threshold (default: 0.4)
channel – Channel type (‘DNA-FISH’ or ‘CENPC’)
- Returns:
(labeled_spots, centroids) or (None, None) if no spots detected
- Return type:
- find_common()[source]
Find Channel 1 spots in chromosomes that also contain Channel 2 spots and calculate Channel 2 intensity.
- Returns:
Labeled image showing chromosomes with both types of spots None: If no spots are found or an error occurs
- Return type:
Note
Requires prior segmentation (self.nuclei must be set)
Requires prior spot detection for both channels
Updates self.common_nuclei with the labeled image
Updates self.df_centroid_dna_fish with spot locations and intensities
- measure_intensity_at_spots(intensity_image, spots_df, channel_name)[source]
Measure intensity values at spot locations for a single channel.
- Parameters:
intensity_image – Image to measure intensities from
spots_df – DataFrame with spot locations (must have ‘Y’ and ‘X’ columns)
channel_name – Name of the channel (‘Channel1’ or ‘Channel2’)
- Returns:
DataFrame with spot locations and their corresponding intensities
- gen_intensity_from_df(intensity_image_ch2, spots_df_ch1, intensity_image_ch1=None, spots_df_ch2=None)[source]
Generate intensity measurements for both channels at each other’s spot locations.
- Parameters:
intensity_image_ch2 – Channel 2 intensity image
spots_df_ch1 – DataFrame with Channel 1 spot locations
intensity_image_ch1 – Channel 1 intensity image (optional)
spots_df_ch2 – DataFrame with Channel 2 spot locations (optional)
- Returns:
DataFrame with both channels’ spot locations and their corresponding intensities
- calculate_intensity_all_cenpc(intensity_image_ch1=None)[source]
Calculate Channel 1 intensity at all Channel 2 spot locations without segmentation.
- Parameters:
intensity_image_ch1 – Optional Channel 1 intensity image. If not provided, uses self.img_dna_fish
- Returns:
- DataFrame containing spot locations and corresponding intensities,
or None if spots or intensity image are missing
- Return type:
pandas.DataFrame
- calculate_intensity_all_dna_fish(intensity_image_ch2=None)[source]
Calculate Channel 2 intensity at all Channel 1 spot locations without segmentation.
- Parameters:
intensity_image_ch2 – Optional Channel 2 intensity image. If not provided, uses self.img_cenpc
- Returns:
- DataFrame containing spot locations and corresponding intensities,
or None if spots or intensity image are missing
- Return type:
pandas.DataFrame
- delete_dna_fish_spots_with_line(viewer)[source]
Delete DNA-FISH spots that intersect with the drawn line or points.
Key Methods:
load_images(folder_path, dapi_id, dna_fish_id, cenpc_id, skip_segmentation)segment_image(image, save_dir=None)detect_spots_cent(image, channel_type, threshold, save_dir=None)find_common()measure_intensity_at_spots(intensity_image, spots_df, channel_name)
BatchProcessor
Handles batch processing of multiple image folders.
- class batch_processor.BatchProcessor(processor, control_widget_dna_fish, control_widget_cenpc)[source]
Bases:
object- Parameters:
processor (ImageProcessor)
Key Methods:
batch_processing(root_folder, dapi_id, dna_fish_id, cenpc_id, skip_segmentation)
SegmentationPostprocessing
Provides post-processing operations for segmentation results.
GUI Components
The main application includes several GUI components built with magicgui and Qt:
Control Widgets
ControlWidgetDNAFISH- DNA-FISH spot detection controlsControlWidgetCENPC- CENP-C spot detection controlsChannelIdentifiers- Channel configuration widgetSegmentDAPIWidget- DAPI segmentation controls
Main Functions
Core analysis functions accessible through the GUI:
load_images()- Load multi-channel imagessegment_image()- Segment chromosomes using Cellposedetect_dna_fish_spots()- Detect DNA-FISH spotsdetect_cenpc_spots()- Detect CENP-C spotsfind_common()- Find overlapping regionsget_intensity_at_cenpc_location()- Measure intensities
Usage Examples
Basic Usage
Here’s how to use the core classes programmatically:
from image_processor import ImageProcessor
from batch_processor import BatchProcessor
# Initialize processor
processor = ImageProcessor()
# Load images
images = processor.load_images(
folder_path="path/to/images",
dapi_id="DAPI",
dna_fish_id="DNA-FISH",
cenpc_id="CENP-C",
skip_segmentation=False
)
# Segment chromosomes
if images:
masks = processor.segment_image(images[0])
# Detect spots
spots_ch1 = processor.detect_spots_cent(
images[1], 'DNA-FISH', threshold=0.4
)
spots_ch2 = processor.detect_spots_cent(
images[2], 'CENP-C', threshold=0.4
)
# Find common regions
common_nuclei = processor.find_common()
# Measure intensities
results = processor.gen_intensity_from_df(
processor.img_cenpc,
processor.df_centroid_dna_fish
)
Batch Processing
For processing multiple folders:
from batch_processor import BatchProcessor
from image_processor import ImageProcessor
# Initialize components
processor = ImageProcessor()
# Mock control widgets (normally from GUI)
class MockWidget:
def __init__(self, threshold):
self.threshold = threshold
def value(self):
return self.threshold
class slider:
def __init__(self, threshold):
self.threshold = threshold
def value(self):
return self.threshold
control_dna_fish = MockWidget(40)
control_cenpc = MockWidget(40)
# Initialize batch processor
batch_processor = BatchProcessor(
processor,
control_dna_fish,
control_cenpc
)
# Run batch processing
batch_processor.batch_processing(
root_folder="path/to/root",
dapi_id="DAPI",
dna_fish_id="DNA-FISH",
cenpc_id="CENP-C",
skip_segmentation=False
)
Custom Analysis
For advanced users who want to modify the analysis pipeline:
import numpy as np
from image_processor import ImageProcessor
from skimage.io import imread
class CustomAnalyzer(ImageProcessor):
def __init__(self):
super().__init__()
def custom_segmentation(self, image, custom_params):
"""Custom segmentation method"""
# Your custom segmentation logic here
pass
def custom_spot_detection(self, image, custom_threshold):
"""Custom spot detection method"""
# Your custom spot detection logic here
pass
def custom_analysis_pipeline(self, folder_path):
"""Complete custom analysis pipeline"""
# Load images
images = self.load_images(folder_path, "DAPI", "CH1", "CH2", False)
# Custom segmentation
masks = self.custom_segmentation(images[0], {})
# Custom spot detection
spots1 = self.custom_spot_detection(images[1], 0.5)
spots2 = self.custom_spot_detection(images[2], 0.5)
# Continue with standard analysis
return self.gen_intensity_from_df(images[2], spots1)
Parameters Reference
Segmentation Parameters
Cellpose Parameters:
model_type: ‘cyto’ or custom model pathdiameter: None (auto-detect) or specific pixel diameterchannels: [0,0] for grayscale inputgpu: True/False for GPU acceleration
Post-processing Parameters:
remove_small_objects: Boolean, removes objects below size thresholdremove_edge_objects: Boolean, removes objects touching bordersfill_holes: Boolean, fills holes in segmented objectssmooth_boundaries: Boolean, applies morphological smoothing
Spot Detection Parameters
Detection Parameters:
threshold: Float 0-1, detection sensitivitymin_distance: Minimum distance between spotsnum_peaks: Maximum number of peaks to detect
Filtering Parameters:
min_intensity: Minimum spot intensitymax_intensity: Maximum spot intensityexclusion_radius: Radius around spots to exclude
Data Structures
The API works with several key data structures:
Spot DataFrames
Spot detection results are returned as pandas DataFrames with columns:
X: X-coordinate of spot centroidY: Y-coordinate of spot centroidintensity: Spot intensity valuelabel: Associated nucleus label
Segmentation Masks
Segmentation results are numpy arrays where:
0: Background pixels1, 2, 3, ...: Individual nucleus labels
Intensity Results
Intensity measurements are returned as DataFrames with:
spot_x,spot_y: Spot coordinatesintensity_ch1,intensity_ch2: Intensity valuesnucleus_label: Associated nucleusfolder: Source folder (for batch processing)
Error Handling
The API includes comprehensive error handling:
try:
results = processor.segment_image(image)
except Exception as e:
print(f"Segmentation failed: {e}")
# Handle error appropriately
Common exceptions:
FileNotFoundError: Image files not foundValueError: Invalid parametersRuntimeError: Cellpose model errorsMemoryError: Insufficient memory for processing
Extension Points
The codebase is designed to be extensible:
Custom Models
Replace the default Cellpose model:
# In image_processor.py, modify segment_image method
def segment_image(self, image, custom_model_path=None):
if custom_model_path:
model = models.CellposeModel(
gpu=True,
pretrained_model=custom_model_path
)
else:
# Use default model
pass
Custom Post-processing
Add custom post-processing steps:
from segmentation_postprocessing import SegmentationPostprocessing
class CustomPostprocessing(SegmentationPostprocessing):
def custom_filter(self, masks, params):
# Your custom filtering logic
return filtered_masks
Custom Visualization
Add custom visualization layers:
# Add custom layers to napari viewer
viewer.add_labels(custom_masks, name='Custom Segmentation')
viewer.add_points(custom_spots, name='Custom Spots')
This API documentation provides the foundation for extending and customizing the Napari Chromosome Analysis toolkit for your specific research needs.