API Reference

This page contains the API reference for all modules in the cryoblob package.

Core Detection Modules

Traditional Blob Detection

Module: blobs

Codes for actually detecting the blobs. The image processing and data I/O files are kept separately. This just deals with preprocessing data and counting blobs.

Functions

  • find_connected_components:

    Pure JAX implementation of 3D connected components labeling.

  • center_of_mass_3d:

    Calculate center of mass for each labeled region in a 3D image.

  • find_particle_coords:

    Find particle coordinates using connected components and center of mass.

  • preprocessing:

    Pre-processes low SNR images to improve contrast of blobs.

  • blob_list_log:

    Detects blobs in an input image using the Laplacian of Gaussian (LoG) method.

cryoblob.blobs.find_connected_components(binary_image, connectivity=6)

Description

Pure JAX implementation of 3D connected components labeling. Uses a two-pass algorithm.

param - binary_image (Bool[Array:

Binary image where True/1 indicates foreground

param “x y z”]):

Binary image where True/1 indicates foreground

param - connectivity (int:

Either 6 (face-connected) or 26 (fully-connected). Default is 6

param optional):

Either 6 (face-connected) or 26 (fully-connected). Default is 6

returns:
    • labels (Integer[Array, “x y z”]) – Array where each connected component has unique integer label

    • num_labels (int) – Number of connected components found

cryoblob.blobs.center_of_mass_3d(image, labels, num_labels)

Description

Calculate center of mass for each labeled region in a 3D image.

param - image (Float[Array:

3D image array

param “x y z”]):

3D image array

param - labels (Integer[Array:

Integer array of labels

param “x y z”]):

Integer array of labels

param - num_labels (int):

Number of labels (excluding background)

returns:

Array of centroid coordinates for each label

rtype:
  • centroids (Float[Array, “n 3”])

cryoblob.blobs.find_particle_coords(results_3D, max_filtered, image_thresh)

Description

Find particle coordinates using connected components and center of mass. Pure JAX implementation.

param - results_3D (Float[Array:

3D array of filter responses

param “x y z”]):

3D array of filter responses

param - max_filtered (Float[Array:

Maximum filtered array

param “x y z”]):

Maximum filtered array

param - image_thresh (scalar_float):

Threshold for peak detection

returns:

Array of particle coordinates

rtype:
  • coords (Float[Array, “n 3”])

cryoblob.blobs.preprocessing(image_orig, return_params=False, exponential=True, logarizer=False, gblur=2, background=0, apply_filter=0)

Description

Pre-processing of low SNR images to improve contrast of blobs.

param - image_orig (Float[Array:

An input image represented as a 2D JAX array.

param “y x”]):

An input image represented as a 2D JAX array.

param - return_params (bool:

A boolean indicating whether to return the processing parameters. Default is False.

param optional):

A boolean indicating whether to return the processing parameters. Default is False.

param - exponential (bool:

A boolean indicating whether to apply an exponential function to the image. Default is True.

param optional):

A boolean indicating whether to apply an exponential function to the image. Default is True.

param - logarizer (bool:

A boolean indicating whether to apply a log function to the image. Default is False.

param optional):

A boolean indicating whether to apply a log function to the image. Default is False.

param - gblur (int:

The standard deviation of the Gaussian filter. Default is 2.

param optional):

The standard deviation of the Gaussian filter. Default is 2.

param - background (int:

The standard deviation of the Gaussian filter for background subtraction. Default is 0.

param optional):

The standard deviation of the Gaussian filter for background subtraction. Default is 0.

param - apply_filter (int:

If greater than 1, a Wiener filter is applied to the image.

param optional):

If greater than 1, a Wiener filter is applied to the image.

returns:

The pre-processed image

rtype:
  • image_proc (Float[Array, “y x”])

cryoblob.blobs.blob_list_log(mrc_image, min_blob_size=5, max_blob_size=20, blob_step=1, downscale=4, std_threshold=6)

Description

Detect blobs of varying sizes in an MRC image using the Laplacian of Gaussian (LoG) method.

param - mrc_image (MRC_Image):

The PyTree containing the image data and metadata.

param - min_blob_size (scalar_num:

Minimum blob size to detect. Defaults to 10.

param optional):

Minimum blob size to detect. Defaults to 10.

param - max_blob_size (scalar_num:

Maximum blob size to detect. Defaults to 100.

param optional):

Maximum blob size to detect. Defaults to 100.

param - blob_step (scalar_num:

Step size between consecutive blob scales. Defaults to 2.

param optional):

Step size between consecutive blob scales. Defaults to 2.

param - downscale (scalar_num:

Factor by which the image is downscaled before detection. Defaults to 4.

param optional):

Factor by which the image is downscaled before detection. Defaults to 4.

param - std_threshold (scalar_num:

Threshold in standard deviations for blob detection. Defaults to 6.

param optional):

Threshold in standard deviations for blob detection. Defaults to 6.

returns:

Array of blob coordinates and sizes, shape [n, 3]. Columns represent (Y, X, Blob size in pixels).

rtype:
  • scaled_coords (Float[Array, “n 3”])

Multi-method Enhanced Detection

Module: multi

Multi-method blob detection for elongated objects and overlapping blobs. Extends the base blob detection with ridge detection for elongated objects and watershed segmentation for overlapping blobs.

Functions

  • hessian_matrix_2d:

    Compute Hessian matrix components for 2D image at given scale.

  • determinant_of_hessian:

    Compute Determinant of Hessian for blob detection with better boundary detection.

  • ridge_detection:

    Detect elongated objects using ridge detection with eigenvalue analysis.

  • multi_scale_ridge_detector:

    Multi-scale ridge detection for various elongated object sizes.

  • distance_transform_euclidean:

    Compute Euclidean distance transform for watershed marker generation.

  • watershed_segmentation:

    Segment overlapping blobs using marker-based watershed algorithm.

  • adaptive_marker_generation:

    Generate watershed markers using distance transform and local maxima.

  • hessian_blob_detection:

    Detect blobs using Determinant of Hessian for better boundary detection.

  • enhanced_blob_detection:

    Combined approach using LoG, ridge detection, and watershed segmentation.

cryoblob.multi.hessian_matrix_2d(image, sigma=1.0)

Description

Compute the Hessian matrix components for 2D image at given scale. Uses Gaussian derivatives to compute second-order partial derivatives.

param - image (Float[Array:

Input image

param “h w”]):

Input image

param - sigma (scalar_float:

Scale parameter for Gaussian derivatives. Default is 1.0

param optional):

Scale parameter for Gaussian derivatives. Default is 1.0

returns:
    • hxx (Float[Array, “h w”]) – Second derivative in x direction (horizontal)

    • hxy (Float[Array, “h w”]) – Mixed second derivative (cross-correlation)

    • hyy (Float[Array, “h w”]) – Second derivative in y direction (vertical)

  • Flow

  • —-

  • - Apply Gaussian smoothing at specified scale

  • - Compute first derivatives using Sobel operators

  • - Compute second derivatives from first derivatives

cryoblob.multi.determinant_of_hessian(image, sigma=1.0)

Description

Compute Determinant of Hessian for blob detection with better boundary detection. DoH provides superior boundary localization compared to LoG for irregular shapes.

param - image (Float[Array:

Input image

param “h w”]):

Input image

param - sigma (scalar_float:

Scale parameter for Gaussian derivatives. Default is 1.0

param optional):

Scale parameter for Gaussian derivatives. Default is 1.0

returns:
    • normalized_det (Float[Array, “h w”]) – Scale-normalized determinant of Hessian response

  • Flow

  • —-

  • - Compute Hessian matrix components

  • - Calculate determinant (det(H) = Hxx * Hyy - Hxy^2)

  • - Apply scale normalization (sigma^4 * det(H))

cryoblob.multi.ridge_detection(image, sigma=1.0, threshold=0.01)

Description

Detect ridges (elongated objects) using eigenvalues of Hessian matrix. Ridges correspond to structures with one large negative eigenvalue.

param - image (Float[Array:

Input image

param “h w”]):

Input image

param - sigma (scalar_float:

Scale parameter for Gaussian derivatives. Default is 1.0

param optional):

Scale parameter for Gaussian derivatives. Default is 1.0

param - threshold (scalar_float:

Ridge strength threshold. Default is 0.01

param optional):

Ridge strength threshold. Default is 0.01

returns:
    • ridge_response (Float[Array, “h w”]) – Ridge detection response map

  • Flow

  • —-

  • - Compute Hessian matrix components

  • - Calculate eigenvalues using trace and determinant

  • - Extract ridge strength as maximum absolute eigenvalue

  • - Apply threshold to create ridge response map

cryoblob.multi.multi_scale_ridge_detector(image, min_scale=1.0, max_scale=10.0, num_scales=10, threshold=0.01)

Description

Multi-scale ridge detection for elongated objects of various sizes. Detects ridges across multiple scales and returns maximum response.

param - image (Float[Array:

Input image

param “h w”]):

Input image

param - min_scale (scalar_float:

Minimum scale parameter. Default is 1.0

param optional):

Minimum scale parameter. Default is 1.0

param - max_scale (scalar_float:

Maximum scale parameter. Default is 10.0

param optional):

Maximum scale parameter. Default is 10.0

param - num_scales (scalar_int:

Number of scales to test. Default is 10

param optional):

Number of scales to test. Default is 10

param - threshold (scalar_float:

Ridge detection threshold. Default is 0.01

param optional):

Ridge detection threshold. Default is 0.01

returns:
    • max_ridge_response (Float[Array, “h w”]) – Maximum ridge response across all scales

  • Flow

  • —-

  • - Generate logarithmic scale sequence

  • - Apply ridge detection at each scale

  • - Take maximum response across scales

cryoblob.multi.distance_transform_euclidean(binary_image)

Description

Compute Euclidean distance transform for watershed marker generation. Calculates minimum distance from each background pixel to nearest foreground pixel.

param - binary_image (Bool[Array:

Binary image where True represents foreground objects

param “h w”]):

Binary image where True represents foreground objects

returns:
    • distance_map (Float[Array, “h w”]) – Euclidean distance transform map

  • Flow

  • —-

  • - Extract coordinates of all foreground pixels

  • - For each background pixel, compute minimum distance to foreground

  • - Set foreground pixels to distance zero

cryoblob.multi.adaptive_marker_generation(binary_image, min_distance=5.0)

Description

Generate watershed markers using distance transform and local maxima detection. Creates seed points for watershed segmentation of overlapping objects.

param - binary_image (Bool[Array:

Binary image of detected blob regions

param “h w”]):

Binary image of detected blob regions

param - min_distance (scalar_float:

Minimum distance threshold for marker placement. Default is 5.0

param optional):

Minimum distance threshold for marker placement. Default is 5.0

returns:
    • markers (Integer[Array, “h w”]) – Marker image with labeled seed regions for watershed

  • Flow

  • —-

  • - Compute distance transform of binary image

  • - Find local maxima in distance transform

  • - Filter maxima by minimum distance threshold

  • - Label connected components to create markers

  • - Set background regions to -1, unlabeled foreground to 0

cryoblob.multi.watershed_segmentation(image, markers, max_iterations=15)

Description

Marker-based watershed segmentation for separating overlapping blobs. Simulates flooding from marked seed points to segment touching objects.

param - image (Float[Array:

Input image (typically gradient magnitude or distance transform)

param “h w”]):

Input image (typically gradient magnitude or distance transform)

param - markers (Integer[Array:

Marker image with labeled seed points

param “h w”]):

Marker image with labeled seed points

param - max_iterations (scalar_int:

Maximum number of flooding iterations. Default is 15

param optional):

Maximum number of flooding iterations. Default is 15

returns:
    • segmented (Integer[Array, “h w”]) – Segmented image with watershed boundaries marked as -1

  • Flow

  • —-

  • - Initialize segmentation with marker labels

  • - Iteratively expand labeled regions to neighboring pixels

  • - Handle conflicts at boundaries between different labels

  • - Stop when no more pixels can be labeled or max iterations reached

cryoblob.multi.hessian_blob_detection(mrc_image, min_blob_size=5, max_blob_size=20, blob_step=1, downscale=4, std_threshold=6)

Description

Detect blobs using Determinant of Hessian for superior boundary detection. DoH provides better localization of blob boundaries compared to LoG method.

param - mrc_image (MRC_Image):

Input MRC image structure

param - min_blob_size (scalar_num:

Minimum blob size to detect. Default is 5

param optional):

Minimum blob size to detect. Default is 5

param - max_blob_size (scalar_num:

Maximum blob size to detect. Default is 20

param optional):

Maximum blob size to detect. Default is 20

param - blob_step (scalar_num:

Step size between consecutive scales. Default is 1

param optional):

Step size between consecutive scales. Default is 1

param - downscale (scalar_num:

Image downscaling factor for computational efficiency. Default is 4

param optional):

Image downscaling factor for computational efficiency. Default is 4

param - std_threshold (scalar_num:

Detection threshold in standard deviations. Default is 6

param optional):

Detection threshold in standard deviations. Default is 6

returns:
    • scaled_coords (Float[Array, “n 3”]) – Detected blob coordinates and sizes [Y_nm, X_nm, Size_nm]

  • Flow

  • —-

  • - Downscale image for computational efficiency

  • - Apply DoH detection across multiple scales

  • - Use 3D connected components for blob extraction

  • - Scale coordinates back to original image dimensions

cryoblob.multi.enhanced_blob_detection(mrc_image, min_blob_size=5, max_blob_size=20, blob_step=1, downscale=4, std_threshold=6, use_ridge_detection=True, use_watershed=True, ridge_threshold=0.01, min_marker_distance=5.0)

Description

Enhanced multi-method blob detection combining Hessian blobs, ridge detection, and watershed segmentation for comprehensive analysis of circular blobs, elongated objects, and overlapping structures.

param - mrc_image (MRC_Image):

Input MRC image structure

param - min_blob_size (scalar_num:

Minimum blob size to detect. Default is 5

param optional):

Minimum blob size to detect. Default is 5

param - max_blob_size (scalar_num:

Maximum blob size to detect. Default is 20

param optional):

Maximum blob size to detect. Default is 20

param - blob_step (scalar_num:

Step size between consecutive scales. Default is 1

param optional):

Step size between consecutive scales. Default is 1

param - downscale (scalar_num:

Image downscaling factor for efficiency. Default is 4

param optional):

Image downscaling factor for efficiency. Default is 4

param - std_threshold (scalar_num:

Detection threshold in standard deviations. Default is 6

param optional):

Detection threshold in standard deviations. Default is 6

param - use_ridge_detection (bool:

Enable ridge detection for elongated objects. Default is True

param optional):

Enable ridge detection for elongated objects. Default is True

param - use_watershed (bool:

Enable watershed segmentation for overlapping blobs. Default is True

param optional):

Enable watershed segmentation for overlapping blobs. Default is True

param - ridge_threshold (scalar_float:

Ridge detection sensitivity threshold. Default is 0.01

param optional):

Ridge detection sensitivity threshold. Default is 0.01

param - min_marker_distance (scalar_float:

Minimum distance between watershed markers. Default is 5.0

param optional):

Minimum distance between watershed markers. Default is 5.0

returns:
    • circular_blobs (Float[Array, “n 3”]) – Circular/irregular blob detections using Hessian method

    • elongated_blobs (Float[Array, “m 3”]) – Elongated object detections using ridge detection

    • watershed_blobs (Float[Array, “k 3”]) – Separated overlapping blob detections using watershed

  • Flow

  • —-

  • - Apply Hessian-based blob detection for general blob shapes

  • - Optionally apply ridge detection for elongated structures

  • - Optionally apply watershed segmentation for overlapping blobs

  • - Return separate detection results for analysis and combination

Image Processing and Utilities

Image Processing

Module: image

Contains the basic functions for image processing, including resizing, filtering. This module will be used for data preprocessing.

Functions:

  • image_resizer:

    Resize an image using a fast resizing algorithm implemented in JAX.

  • resize_x:

    Resize image along y-axis by independently resampling each column.

  • gaussian_kernel:

    Create a normalized 2D Gaussian kernel.

  • apply_gaussian_blur:

    Apply Gaussian blur to an image using convolution in JAX.

  • difference_of_gaussians:

    Applies Difference of Gaussians (DoG) filtering to enhance circular blobs.

  • laplacian_of_gaussian:

    Applies Laplacian of Gaussian (LoG) filtering to an input image.

  • laplacian_kernel:

    Create a Laplacian kernel for edge detection in a JAX-compatible manner.

  • exponential_kernel:

    Create an exponential kernel for image processing.

  • perona_malik:

    Perform edge-preserving denoising using the Perona-Malik anisotropic diffusion.

  • histogram:

    Calculate the histogram of an image.

  • equalize_hist:

    Perform histogram equalization on an image using JAX.

  • equalize_adapthist:

    Perform adaptive histogram equalization on an image using JAX.

  • wiener:

    Perform Wiener filtering on an image using JAX.

cryoblob.image.image_resizer(orig_image, new_sampling)

Description

Resize an image using a fast resizing algorithm implemented in JAX. If a 3D stack is provided, the function will sum along the last dimension.

param - orig_image (Real[Array:

The original image to be resized. It should be a 2D JAX array or 3D stack.

param “y x”] | Real[Array:

The original image to be resized. It should be a 2D JAX array or 3D stack.

param “y x c”]):

The original image to be resized. It should be a 2D JAX array or 3D stack.

param - new_sampling (scalar_num | Real[Array:

The new sampling rate for resizing the image. It can be a single float value or a tuple of two float values representing the sampling rates for the x and y axes respectively. - If a single value is provided, it will be applied to both axes. - If new_sampling is greater than 1, the image will be downsampled. - If new_sampling is less than 1, the image will be upsampled.

param “2”]):

The new sampling rate for resizing the image. It can be a single float value or a tuple of two float values representing the sampling rates for the x and y axes respectively. - If a single value is provided, it will be applied to both axes. - If new_sampling is greater than 1, the image will be downsampled. - If new_sampling is less than 1, the image will be upsampled.

returns:

The resized image.

rtype:
  • resampled_image (Float[Array, “a b”])

cryoblob.image.resize_x(x_image, new_x_len)

Description

Resize image along y-axis by independently resampling each column. Uses lax.scan over the y-dimension, then vmap over x-dimension.

param - x_image (Num[Array:

Image to resize (y by x)

param “y x”]):

Image to resize (y by x)

param - new_x_len (scalar_int):

Target number of columns

returns:

Resized image (new_y by x)

rtype:
  • resized (Float[Array, “y new_x”])

cryoblob.image.gaussian_kernel(size, sigma)

Description

Create a normalized 2D Gaussian kernel.

param - size (scalar_int):

Kernel size (size x size). Must be odd.

param - sigma (scalar_float):

Standard deviation of the Gaussian distribution.

returns:

Normalized 2D Gaussian kernel.

rtype:
  • kernel (Float[Array, “size size”])

cryoblob.image.apply_gaussian_blur(image, sigma=1.0, kernel_size=5, mode='same')

Description

Apply Gaussian blur to an image using convolution in JAX.

param - image (Real[Array:

Input image.

param “y x”]):

Input image.

param - sigma (scalar_float:

Standard deviation for Gaussian kernel. Defaults to 1.0.

param optional):

Standard deviation for Gaussian kernel. Defaults to 1.0.

param - kernel_size (scalar_int:

Size of Gaussian kernel. Must be odd. Defaults to 5.

param optional):

Size of Gaussian kernel. Must be odd. Defaults to 5.

param - mode (Literal[“full”:

Convolution mode. Defaults to “same”.

param “valid”:

Convolution mode. Defaults to “same”.

param “same”]):

Convolution mode. Defaults to “same”.

returns:

Blurred image.

rtype:
  • blurred (Float[Array, “yp xp”])

cryoblob.image.difference_of_gaussians(image, sigma1, sigma2, sampling=1, hist_stretch=True, normalized=True)

Description

Applies Difference of Gaussians (DoG) filtering to enhance circular blobs.

param - image (Real[Array:

Input 2D image.

param “y x”]):

Input 2D image.

param - sigma1 (scalar_num):

Standard deviation of the first Gaussian (smaller).

param - sigma2 (scalar_num):

Standard deviation of the second Gaussian (larger).

param - sampling (scalar_num:

Downsampling factor; 1 means no resizing. Default is 1.

param optional):

Downsampling factor; 1 means no resizing. Default is 1.

param - hist_stretch (bool:

Apply histogram stretching if True. Default is True.

param optional):

Apply histogram stretching if True. Default is True.

param - normalized (bool:

Normalize filtered output by sigma2 if True. Default is True.

param optional):

Normalize filtered output by sigma2 if True. Default is True.

returns:
    • dog_filtered (Float[Array, “y x”]) – DoG-filtered image.

  • Flow

  • —-

    • Downsamples image if sampling ≠ 1 (JIT-safe way).

  • - Histogram stretch if requested.

  • - Create arithmetic-enforced DoG kernel.

  • - Convolve the image with DoG kernel.

  • - Normalize output if required.

cryoblob.image.log_kernel(size, sigma, kernel_min=3)

Description

Create a Laplacian of Gaussian kernel for edge detection.

param - size (int):

Kernel size, enforced positive and odd for ‘gaussian’ mode.

param - sigma (scalar_float):

Gaussian standard deviation for LoG kernel.

param - kernel_min (int:

Maximum kernel size (default is 3). This is used to enforce minimum kernel size.

param optional):

Maximum kernel size (default is 3). This is used to enforce minimum kernel size.

returns:

Laplacian kernel.

rtype:
  • kernel (Float[Array, “size size”])

cryoblob.image.exponential_kernel(arr, k)

Description

Create an exponential kernel for image processing.

param - arr (Float[Array:

Input array

param “H W”]):

Input array

param - k (scalar_float):

Exponential decay constant

returns:

Exponential kernel

rtype:
  • kernel (Float[Array, “H W”])

cryoblob.image.perona_malik(image, num_iter, kappa, gamma=0.1, conduction_fn=jaxtyping.jaxtyped)

Perform edge-preserving denoising using the Perona-Malik anisotropic diffusion.

Parameters:
  • (Float[Array (- image) – Input noisy image.

  • W"]) ("H) – Input noisy image.

  • (scalar_int) (- num_iter) – Number of diffusion iterations.

  • (scalar_float) (- kappa) – Conductance coefficient controlling sensitivity to edges.

  • (scalar_float (- gamma) – Diffusion rate (0 < gamma <= 0.25 for stability), default is 0.1.

  • optional) – Diffusion rate (0 < gamma <= 0.25 for stability), default is 0.1.

  • (Callable (- conduction_fn) – Conductivity function, defaults to exponential.

  • optional) – Conductivity function, defaults to exponential.

Returns:

Edge-preserved denoised image.

Return type:

  • denoised_image (Float[Array, “H W”])

Notes

The Perona-Malik equation is given by: u_t = gamma * div(c * grad(u)) + u where: - u is the input image - t is time - gamma is the diffusion rate - c is the conductivity function - grad is the gradient operator - div is the divergence operator

The conductivity function c is typically an exponential function: c(delta) = exp(-delta^2 / kappa^2) where delta is the difference between neighboring pixels.

Perona, Pietro, Takahiro Shiota, and Jitendra Malik. “Anisotropic diffusion.” Geometry-driven diffusion in computer vision (1994): 73-92.

cryoblob.image.histogram(image, bins=256, range_limits=None)

Calculate histogram from input image data.

Parameters:
  • (Real[Array (- image) – Input array (any shape), flattened internally.

  • "..."]) – Input array (any shape), flattened internally.

  • (scalar_int (- bins) – Number of histogram bins.

  • optional) – Number of histogram bins.

  • (Tuple[scalar_float (- range_limits) – Min and max range for bins.

  • scalar_float] – Min and max range for bins.

  • optional) – Min and max range for bins.

Returns:

Histogram counts per bin.

Return type:

  • hist (Num[Array, “bins”])

cryoblob.image.equalize_hist(image, nbins=256, mask=None)

Description

Perform histogram equalization on an image using JAX.

param - image (Real[Array:

Input image to equalize

param “h w”]):

Input image to equalize

param - nbins (scalar_int:

Number of bins for histogram. Default is 256

param optional):

Number of bins for histogram. Default is 256

param - mask (Real[Array:

Optional mask for selective equalization. Default is None (use all pixels)

param “h w”]:

Optional mask for selective equalization. Default is None (use all pixels)

param optional):

Optional mask for selective equalization. Default is None (use all pixels)

returns:

Histogram equalized image

rtype:
  • equalized (Float[Array, “h w”])

cryoblob.image.equalize_adapthist(image, kernel_size=8, clip_limit=0.01, nbins=256)

Description

Perform Contrast Limited Adaptive Histogram Equalization (CLAHE).

param - image (Real[Array:

Input image.

param “h w”]):

Input image.

param - kernel_size (scalar_int:

Size of local regions for histogram equalization. Default is 8.

param optional):

Size of local regions for histogram equalization. Default is 8.

param - clip_limit (scalar_float:

Clipping limit for histogram. Higher values amplify contrast more strongly. Default is 0.01.

param optional):

Clipping limit for histogram. Higher values amplify contrast more strongly. Default is 0.01.

param - nbins (scalar_int:

Number of bins for the histogram. Default is 256.

param optional):

Number of bins for the histogram. Default is 256.

returns:

Image after applying CLAHE.

rtype:
  • equalized_final (Float[Array, “h w”])

Notes

CLAHE performs localized histogram equalization to improve image contrast without amplifying noise excessively. The algorithm:

  • Divides the image into small regions (tiles).

  • Performs local histogram equalization on each tile separately.

  • Clips histograms at the specified limit to prevent noise amplification.

  • Interpolates results to produce a smoothly equalized image.

cryoblob.image.wiener(img, kernel_size=3, noise=None)

Description

JAX implementation of Wiener filter for noise reduction. This is similar to scipy.signal.wiener.

param - img (Float[Array:

The input image to be filtered

param “h w”]):

The input image to be filtered

param - kernel_size (int or tuple:

The size of the sliding window for local statistics. If tuple, represents (height, width). Default is 3

param optional):

The size of the sliding window for local statistics. If tuple, represents (height, width). Default is 3

param - noise (scalar_float:

The noise power. If None, uses the average of the local variance. Default is None

param optional):

The noise power. If None, uses the average of the local variance. Default is None

returns:

The filtered output with the same shape as input

rtype:
  • filtered (Float[Array, “h w”])

Notes

The Wiener filter is optimal in terms of the mean square error. It estimates the local mean and variance around each pixel.

Adaptive Processing

Module: adapt

Contains adaptive image processing methods that take advantage of JAX’s automatic differentiation capabilities.

Functions

  • adaptive_wiener:

    Adaptive Wiener filter that optimizes the noise estimate using gradient descent.

  • adaptive_threshold:

    Adaptively optimizes thresholding parameters using gradient descent to produce a differentiably thresholded image.

cryoblob.adapt.adaptive_wiener(img, target, kernel_size=3, initial_noise=0.1, learning_rate=0.01, iterations=100)

Adaptive Wiener filter that optimizes the noise estimate using gradient descent.

Parameters:
  • (Float[Array (- target) – Noisy input image.

  • w"]) ("h) – Noisy input image.

  • (Float[Array – A target image or reference image used for optimization.

  • w"]) – A target image or reference image used for optimization.

  • Tuple[int (- kernel_size (scalar_int |) – Window size for Wiener filter. Default is 3.

  • int] – Window size for Wiener filter. Default is 3.

  • optional) – Window size for Wiener filter. Default is 3.

  • (scalar_float (- learning_rate) – Initial guess for noise parameter. Default is 0.1.

  • optional) – Initial guess for noise parameter. Default is 0.1.

  • (scalar_float – Learning rate for optimization. Default is 0.01.

  • optional) – Learning rate for optimization. Default is 0.01.

  • (scalar_int (- iterations) – Number of optimization steps. Default is 100.

  • optional) – Number of optimization steps. Default is 100.

Returns:

    • filtered_img (Float[Array, “h w”]) – Wiener filtered image with optimized noise parameter.

    • optimized_noise (scalar_float) – The optimized noise parameter.

Return type:

beartype.typing.Tuple.(jaxtyping.Float.(jaxtyping.Array, ‘h w’), beartype.typing.Union.(<class ‘float’>, jaxtyping.Float.(jaxtyping.Array, ‘’)))

cryoblob.adapt.adaptive_threshold(img, target, initial_threshold=0.5, initial_slope=10.0, learning_rate=0.01, iterations=100)

Description

Adaptively optimizes thresholding parameters using gradient descent to produce a differentiably thresholded image.

param - img (Float[Array:

The input image to threshold.

param “h w”]):

The input image to threshold.

param - target (Float[Array:

A reference binary image for supervised parameter optimization.

param “h w”]):

A reference binary image for supervised parameter optimization.

param - initial_threshold (scalar_float:

Initial guess for the threshold parameter. Default is 0.5.

param optional):

Initial guess for the threshold parameter. Default is 0.5.

param - initial_slope (scalar_float:

Initial guess for the slope controlling sigmoid steepness. Default is 10.0.

param optional):

Initial guess for the slope controlling sigmoid steepness. Default is 10.0.

param - learning_rate (scalar_float:

The learning rate used during gradient optimization. Default is 0.01.

param optional):

The learning rate used during gradient optimization. Default is 0.01.

param - iterations (scalar_int:

Number of iterations for gradient optimization. Default is 100.

param optional):

Number of iterations for gradient optimization. Default is 100.

returns:
    • thresholded_img (Float[Array, “h w”]) – The image after differentiable thresholding using optimized parameters.

    • optimized_threshold (scalar_float) – The optimized threshold parameter.

    • optimized_slope (scalar_float) – The optimized slope parameter.

  • Flow

  • —-

    • sigmoid_threshold – Applies a sigmoid function to the input image.

    • threshold_loss_fn – Computes the loss between the thresholded image and the target.

    • step – Performs a single optimization step.

    • optimized_params – Optimizes threshold and slope parameters.

    • thresholded_img – Applies the optimized thresholding parameters to the

    input image.

Data I/O and Visualization

File Operations

Module: files

Contains the codes for interfacing with data files. One goal here is to separate the Python code from the JAX code. Thus most of the necessary outward facing code, which is necessarily in Python, is here.

Functions

  • file_params:

    Get the parameters for the file organization.

  • load_mrc:

    Reads an MRC-format cryo-EM file, extracting image data and metadata.

  • process_single_file:

    Process a single file for blob detection with memory optimization.

  • process_batch_of_files:

    Process a batch of files in parallel with memory optimization.

  • folder_blobs:

    Process a folder of images for blob detection with memory optimization.

  • estimate_batch_size:

    Estimate optimal batch size for processing MRC files based on available memory.

  • estimate_memory_usage:

    Estimate memory usage in GB for processing a single MRC file.

  • get_optimal_batch_size:

    Get optimal batch size by sampling multiple files from the list.

cryoblob.files.file_params()

Description

Run this at the beginning to generate the dict This gives both the absolute and relative paths on how the files are organized.

returns:
    • main_directory (str) – the main directory where the package is located.

    • folder_structure (dict) – where the files and data are stored, as read

    from the organization.json file.

cryoblob.files.load_mrc(filepath)[source]

Description

Reads an MRC-format cryo-EM file from the specified path, extracting image data and relevant metadata. All numeric data are converted into JAX arrays and wrapped into a structured MRC_Image PyTree, compatible with JAX’s functional programming paradigm.

param - filepath (str):

Path to the MRC file to be loaded.

returns:
  • image_data: Image array (2D or 3D).

  • voxel_size: Array containing voxel dimensions in

    Å (Z, Y, X).

  • origin: Array indicating the origin coordinates from the

    header (Z, Y, X).

  • data_min: Minimum pixel value.

  • data_max: Maximum pixel value.

  • data_mean: Mean pixel value.

  • mode: Integer code representing data type

    (e.g., 0=int8, 1=int16, 2=float32).

rtype:

MRC_Image (A PyTree containing)

Examples

>>> mrc_image = load_mrc("example.mrc")
>>> print(mrc_image.voxel_size)
Array([1.2, 1.2, 1.2], dtype=float32)

Notes

  • This function uses the mrcfile library for parsing MRC files.

  • The resulting PyTree structure (MRC_Image) is explicitly

    designed for use in JAX-based image processing pipelines.

cryoblob.files.process_single_file(file_path, preprocessing_config, blob_downscale, stream_mode=True)

Description

Process a single MRC file for blob detection with memory optimization and validated preprocessing configuration.

param - file_path (str):

Path to the MRC image file to process

param - preprocessing_config (PreprocessingConfig):

Validated preprocessing configuration containing all processing parameters

param - blob_downscale (scalar_float):

Downscaling factor applied during blob detection to reduce computational load

param - stream_mode (bool:

Whether to use memory-mapped file access for large files to reduce memory usage. Default is True

param optional):

Whether to use memory-mapped file access for large files to reduce memory usage. Default is True

returns:
    • scaled_blobs (Float[Array, “n 3”]) – Array of detected blob coordinates and sizes where each row contains

    [Y_position_nm, X_position_nm, Size_nm]

    • file_path (str) – Original file path for tracking processed files

raises Exception::

Returns empty array and original file path if processing fails, with error message printed to console

Notes

The function uses streaming mode for large files to reduce memory usage and immediately releases file handles after reading. All intermediate arrays are explicitly deleted to manage GPU memory efficiently.

cryoblob.files.process_batch_of_files(file_batch, preprocessing_config, blob_downscale)

Process a batch of files in parallel with memory optimization.

Parameters:
  • (List[str]) (- file_batch) – List of file paths to process

  • (Dict) (- preprocessing_kwargs) – Preprocessing parameters

  • (float) (- blob_downscale) – Downscaling factor

Returns:

List of (blobs, file_path) tuples

Return type:

  • results (List[Tuple[Array, str]])

cryoblob.files.folder_blobs(folder_location, file_type='mrc', blob_downscale=7.0, target_memory_gb=4.0, stream_large_files=True, **kwargs)

Description

Process a folder of MRC images for blob detection with memory optimization and validated preprocessing configuration. Automatically manages batch processing and memory usage to prevent GPU memory overflow.

param - folder_location (str):

Path to folder containing MRC images to process

param - file_type (Literal[“mrc”]:

File extension to search for in the folder. Default is “mrc”

param optional):

File extension to search for in the folder. Default is “mrc”

param - blob_downscale (scalar_float:

Downscaling factor applied during blob detection. Default is 7.0

param optional):

Downscaling factor applied during blob detection. Default is 7.0

param - target_memory_gb (scalar_float:

Target GPU memory usage in GB for batch size optimization. Default is 4.0

param optional):

Target GPU memory usage in GB for batch size optimization. Default is 4.0

param - stream_large_files (bool:

Whether to use memory-mapped file access for large files. Default is True

param optional):

Whether to use memory-mapped file access for large files. Default is True

param - **kwargs:

Additional preprocessing parameters passed to PreprocessingConfig. Valid options: exponential, logarizer, gblur, background, apply_filter

returns:

DataFrame containing detected blob information with columns: [‘File Location’, ‘Center Y (nm)’, ‘Center X (nm)’, ‘Size (nm)’]

rtype:
  • blob_dataframe (pd.DataFrame)

raises ValueError::

If preprocessing parameters are invalid according to PreprocessingConfig validation

Notes

Memory Management: - Uses batch processing to control memory usage - Automatically adjusts batch size based on available memory - Clears device memory between batches - Streams large files if needed - Efficiently handles intermediate results

The function processes files in batches to prevent memory overflow and provides a progress bar to track processing status. Empty folders return an empty DataFrame with the expected column structure.

cryoblob.files.estimate_batch_size(sample_file_path, target_memory_gb=4.0, safety_factor=0.7, processing_overhead=3.0)

Description

Estimate optimal batch size for processing MRC files based on available memory and file characteristics. This function analyzes a sample file to estimate memory requirements and calculates the maximum number of files that can be processed simultaneously without exceeding memory limits.

param - sample_file_path (str):

Path to a representative MRC file for size estimation

param - target_memory_gb (scalar_float:

Target GPU memory usage in GB. Default is 4.0

param optional):

Target GPU memory usage in GB. Default is 4.0

param - safety_factor (scalar_float:

Safety factor to prevent memory overflow (0.0-1.0). Default is 0.7 (use 70% of target memory)

param optional):

Safety factor to prevent memory overflow (0.0-1.0). Default is 0.7 (use 70% of target memory)

param - processing_overhead (scalar_float:

Memory overhead multiplier for processing operations. Default is 3.0 (processing uses 3x the raw data size)

param optional):

Memory overhead multiplier for processing operations. Default is 3.0 (processing uses 3x the raw data size)

returns:

Recommended batch size for processing

rtype:
  • batch_size (scalar_int)

Notes

The estimation considers: - Raw file size in memory (dtype conversion) - Preprocessing operations (filtering, transformations) - Blob detection memory requirements - JAX compilation overhead - Intermediate array storage

Memory estimation formula: ` per_file_memory = file_size * processing_overhead available_memory = target_memory_gb * safety_factor * 1e9 batch_size = max(1, available_memory // per_file_memory) `

Examples

>>> batch_size = estimate_batch_size("sample.mrc", target_memory_gb=8.0)
>>> print(f"Recommended batch size: {batch_size}")
cryoblob.files.estimate_memory_usage(file_path, include_preprocessing=True, include_blob_detection=True)

Description

Estimate memory usage in GB for processing a single MRC file.

param - file_path (str):

Path to MRC file

param - include_preprocessing (bool:

Include memory for preprocessing operations. Default is True

param optional):

Include memory for preprocessing operations. Default is True

param - include_blob_detection (bool:

Include memory for blob detection. Default is True

param optional):

Include memory for blob detection. Default is True

returns:

Estimated memory usage in GB

rtype:
  • memory_gb (scalar_float)

cryoblob.files.get_optimal_batch_size(file_list, target_memory_gb=4.0, sample_fraction=0.1)

Description

Get optimal batch size by sampling multiple files from the list.

param - file_list (list[str]):

List of file paths to process

param - target_memory_gb (scalar_float:

Target memory usage in GB. Default is 4.0

param optional):

Target memory usage in GB. Default is 4.0

param - sample_fraction (scalar_float:

Fraction of files to sample for estimation. Default is 0.1

param optional):

Fraction of files to sample for estimation. Default is 0.1

returns:

Optimal batch size

rtype:
  • batch_size (scalar_int)

Visualization

Module: files

Contains the codes for interfacing with data files. One goal here is to separate the Python code from the JAX code. Thus most of the necessary outward facing code, which is necessarily in Python, is here.

Functions

  • plot_mrc:

    Plot MRC image data using Matplotlib with optional scaling and scalebar.

cryoblob.plots.plot_mrc(mrc_image, image_size=(15, 15), cmap='magma', mode='plain')

Description

Plot an MRC image using Matplotlib with an optional scaling mode and scalebar.

param - mrc_image (MRC_Image):

The PyTree structure containing image data and voxel metadata.

param - image_size (Tuple[scalar_int:

Size of the plotted figure (width, height) in inches. Default is (15, 15).

param scalar_int]:

Size of the plotted figure (width, height) in inches. Default is (15, 15).

param optional):

Size of the plotted figure (width, height) in inches. Default is (15, 15).

param - cmap (str:

The Matplotlib colormap to use. Default is “viridis”.

param optional):

The Matplotlib colormap to use. Default is “viridis”.

param - mode (str:

Mode of visualization: - “plain”: Plot image data without modifications. - “log”: Plot logarithmically scaled image data. - “exp”: Plot exponentially scaled image data. Default is “plain”.

param optional):

Mode of visualization: - “plain”: Plot image data without modifications. - “log”: Plot logarithmically scaled image data. - “exp”: Plot exponentially scaled image data. Default is “plain”.

returns:

Displays the plot.

rtype:

None

Examples

>>> plot_mrc(mrc_image, image_size=(10, 10), cmap="viridis", mode="log")

Configuration and Types

Parameter Validation

Module: valid

JAX PyTree factory functions for configuration management in the cryoblob preprocessing pipeline. This module provides type-safe validation using JAX’s functional approach with jax.lax.cond for preprocessing parameters, file paths, and blob detection configurations.

Functions

  • make_mrc_image:

    Factory function to create an MRC_Image instance.

  • make_preprocessing_config:

    Factory function for preprocessing configuration PyTree

  • make_blob_detection_config:

    Factory function for blob detection configuration PyTree

  • make_file_processing_config:

    Factory function for file processing configuration PyTree

  • make_mrc_metadata:

    Factory function for MRC metadata PyTree

  • make_ridge_detection_config:

    Factory function for ridge detection configuration PyTree

  • make_watershed_config:

    Factory function for watershed configuration PyTree

  • make_enhanced_blob_detection_config:

    Factory function for enhanced blob detection configuration PyTree

  • make_hessian_blob_config:

    Factory function for Hessian blob detection configuration PyTree

  • make_adaptive_filter_config:

    Factory function for adaptive filter configuration PyTree

cryoblob.valid.make_mrc_image(image_data, voxel_size, origin, data_min, data_max, data_mean, mode)

Description

Factory function to create an MRC_Image instance.

param - image_data (Num[Array:

The image data array from the MRC file. Can be 2D or 3D.

param “H W”] | Num[Array:

The image data array from the MRC file. Can be 2D or 3D.

param “D H W”]):

The image data array from the MRC file. Can be 2D or 3D.

param - voxel_size (Float[Array:

Voxel size in the order (Z, Y, X).

param “3”]):

Voxel size in the order (Z, Y, X).

param - origin (Float[Array:

Origin coordinates from the MRC file header (Z, Y, X).

param “3”]):

Origin coordinates from the MRC file header (Z, Y, X).

param - data_min (scalar_float):

Minimum value of image data (as stored in header).

param - data_max (scalar_float):

Maximum value of image data (as stored in header).

param - data_mean (scalar_float):

Mean value of image data (as stored in header).

param - mode (scalar_int):

Data type mode from MRC header (e.g., 0: int8, 2: float32).

returns:

An instance of the MRC_Image PyTree structure.

rtype:
  • MRC_Image

cryoblob.valid.make_preprocessing_config(exponential=True, logarizer=False, gblur=2, background=0, apply_filter=0)[source]

Factory function to create a PreprocessingConfig PyTree with validation.

Parameters:
  • exponential (bool) – Apply exponential function to enhance contrast (default: True)

  • logarizer (bool) – Apply logarithmic transformation (default: False)

  • gblur (int) – Gaussian blur sigma, 0 means no blur (default: 2, range: 0-50)

  • background (int) – Background subtraction sigma, 0 means no subtraction (default: 0, range: 0-100)

  • apply_filter (int) – Wiener filter kernel size, 0 means no filter (default: 0, range: 0-20)

Returns:

Validated preprocessing configuration PyTree

Return type:

PreprocessingConfig

Raises:

ValueError – If validation fails

cryoblob.valid.make_blob_detection_config(min_sigma=1.0, max_sigma=50.0, num_sigma=10, threshold=0.01, exclude_border=0)[source]

Factory function to create a BlobDetectionConfig PyTree with validation.

Parameters:
  • min_sigma (float) – Minimum sigma for Laplacian of Gaussian (default: 1.0)

  • max_sigma (float) – Maximum sigma for Laplacian of Gaussian (default: 50.0)

  • num_sigma (int) – Number of sigma values to test (default: 10)

  • threshold (float) – Detection threshold (default: 0.01)

  • exclude_border (int) – Pixels to exclude from border (default: 0)

Returns:

Validated blob detection configuration PyTree

Return type:

BlobDetectionConfig

cryoblob.valid.make_file_processing_config(batch_size=4, memory_limit_gb=8.0)[source]

Factory function to create a FileProcessingConfig PyTree with validation.

Parameters:
  • batch_size (int) – Number of files to process in parallel (default: 4)

  • memory_limit_gb (float) – Memory limit in GB (default: 8.0)

Returns:

Validated file processing configuration PyTree

Return type:

FileProcessingConfig

cryoblob.valid.make_mrc_metadata(nx, ny, nz, mode, dmin, dmax, dmean)[source]

Factory function to create an MRCMetadata PyTree with validation.

Parameters:
  • nx (int) – Number of columns

  • ny (int) – Number of rows

  • nz (int) – Number of sections

  • mode (int) – Data type

  • dmin (float) – Minimum density value

  • dmax (float) – Maximum density value

  • dmean (float) – Mean density value

Returns:

Validated MRC metadata PyTree

Return type:

MRCMetadata

cryoblob.valid.make_adaptive_filter_config(kernel_size=5, noise_estimate=0.01, iterations=10)[source]

Factory function to create an AdaptiveFilterConfig PyTree with validation.

Parameters:
  • kernel_size (int) – Size of the filter kernel (default: 5)

  • noise_estimate (float) – Initial noise estimate (default: 0.01)

  • iterations (int) – Number of adaptation iterations (default: 10)

Returns:

Validated adaptive filter configuration PyTree

Return type:

AdaptiveFilterConfig

cryoblob.valid.make_ridge_detection_config(min_scale=1.0, max_scale=10.0, scale_step=0.5, threshold=0.1)[source]

Factory function to create a RidgeDetectionConfig PyTree with validation.

Parameters:
  • min_scale (float) – Minimum scale for ridge detection (default: 1.0)

  • max_scale (float) – Maximum scale for ridge detection (default: 10.0)

  • scale_step (float) – Step size for scale space (default: 0.5)

  • threshold (float) – Detection threshold (default: 0.1)

Returns:

Validated ridge detection configuration PyTree

Return type:

RidgeDetectionConfig

cryoblob.valid.make_watershed_config(min_distance=10, threshold_abs=None, compactness=0.0)[source]

Factory function to create a WatershedConfig PyTree with validation.

Parameters:
  • min_distance (int) – Minimum distance between markers (default: 10)

  • threshold_abs (Optional[float]) – Absolute threshold for markers (default: None)

  • compactness (float) – Compactness parameter for watershed (default: 0.0)

Returns:

Validated watershed configuration PyTree

Return type:

WatershedConfig

cryoblob.valid.make_hessian_blob_config(min_sigma=1.0, max_sigma=30.0, num_sigma=10, threshold=0.01)[source]

Factory function to create a HessianBlobConfig PyTree with validation.

Parameters:
  • min_sigma (float) – Minimum sigma for scale space (default: 1.0)

  • max_sigma (float) – Maximum sigma for scale space (default: 30.0)

  • num_sigma (int) – Number of scales to test (default: 10)

  • threshold (float) – Detection threshold (default: 0.01)

Returns:

Validated Hessian blob detection configuration PyTree

Return type:

HessianBlobConfig

cryoblob.valid.make_enhanced_blob_detection_config(min_blob_size=5.0, max_blob_size=50.0, detection_threshold=0.05, use_ridge_detection=True, use_watershed=True)[source]

Factory function to create an EnhancedBlobDetectionConfig PyTree with validation.

Parameters:
  • min_blob_size (float) – Minimum expected blob size (default: 5.0)

  • max_blob_size (float) – Maximum expected blob size (default: 50.0)

  • detection_threshold (float) – Overall detection threshold (default: 0.05)

  • use_ridge_detection (bool) – Enable ridge detection for elongated objects (default: True)

  • use_watershed (bool) – Enable watershed for overlapping blobs (default: True)

Returns:

Validated enhanced blob detection configuration PyTree

Return type:

EnhancedBlobDetectionConfig

Type Definitions

Module: types

A single location for storing commonly used type aliases and PyTrees along with factory functions for creating them.

Types

  • scalar_float:

    Zero dimensional floating point number

  • scalar_int:

    Zero dimensional integer.

  • scalar_num:

    Zero dimensional number, that can either be a floating point number or an integer.

  • non_jax_number:

    A number that is not a JAX array. This is because even single number are stored as 0D JAX arrays.

PyTrees

  • MRC_Image:

    A PyTree structure for MRC images. Contains the image data and metadata.

  • PreprocessingConfig:

    PyTree for image preprocessing parameters

  • BlobDetectionConfig:

    PyTree for blob detection parameters

  • FileProcessingConfig:

    PyTree for file processing and batch operations

  • MRCMetadata:

    PyTree for MRC file metadata

  • RidgeDetectionConfig:

    PyTree for ridge detection parameters

  • WatershedConfig:

    PyTree for watershed segmentation parameters

  • EnhancedBlobDetectionConfig:

    PyTree for enhanced blob detection combining multiple methods

  • HessianBlobConfig:

    PyTree for Hessian-based blob detection

  • AdaptiveFilterConfig:

    PyTree for adaptive filtering parameters

class cryoblob.types.PreprocessingConfig(*args, **kwargs)[source]

Bases: NamedTuple

PyTree for image preprocessing parameters.

exponential

Apply exponential function to enhance contrast

Type:

bool

logarizer

Apply logarithmic transformation

Type:

bool

gblur

Gaussian blur sigma, 0 means no blur

Type:

int

background

Background subtraction sigma, 0 means no subtraction

Type:

int

apply_filter

Wiener filter kernel size, 0 means no filter

Type:

int

exponential: jaxtyping.Bool.(jaxtyping.Array, '')
logarizer: jaxtyping.Bool.(jaxtyping.Array, '')
gblur: jaxtyping.Int.(jaxtyping.Array, '')
background: jaxtyping.Int.(jaxtyping.Array, '')
apply_filter: jaxtyping.Int.(jaxtyping.Array, '')
class cryoblob.types.BlobDetectionConfig(*args, **kwargs)[source]

Bases: NamedTuple

PyTree for blob detection parameters.

min_sigma

Minimum sigma for Laplacian of Gaussian

Type:

float

max_sigma

Maximum sigma for Laplacian of Gaussian

Type:

float

num_sigma

Number of sigma values to test

Type:

int

threshold

Detection threshold

Type:

float

exclude_border

Pixels to exclude from border

Type:

int

min_sigma: jaxtyping.Float.(jaxtyping.Array, '')
max_sigma: jaxtyping.Float.(jaxtyping.Array, '')
num_sigma: jaxtyping.Int.(jaxtyping.Array, '')
threshold: jaxtyping.Float.(jaxtyping.Array, '')
exclude_border: jaxtyping.Int.(jaxtyping.Array, '')
class cryoblob.types.FileProcessingConfig(*args, **kwargs)[source]

Bases: NamedTuple

PyTree for file processing and batch operations.

batch_size

Number of files to process in parallel

Type:

int

memory_limit_gb

Memory limit in GB

Type:

float

batch_size: jaxtyping.Int.(jaxtyping.Array, '')
memory_limit_gb: jaxtyping.Float.(jaxtyping.Array, '')
class cryoblob.types.MRCMetadata(*args, **kwargs)[source]

Bases: NamedTuple

PyTree for MRC file metadata.

nx

Number of columns (fastest changing)

Type:

int

ny

Number of rows

Type:

int

nz

Number of sections (slowest changing)

Type:

int

mode

Data type (0=int8, 1=int16, 2=float32, etc.)

Type:

int

dmin

Minimum density value

Type:

float

dmax

Maximum density value

Type:

float

dmean

Mean density value

Type:

float

nx: jaxtyping.Int.(jaxtyping.Array, '')
ny: jaxtyping.Int.(jaxtyping.Array, '')
nz: jaxtyping.Int.(jaxtyping.Array, '')
mode: jaxtyping.Int.(jaxtyping.Array, '')
dmin: jaxtyping.Float.(jaxtyping.Array, '')
dmax: jaxtyping.Float.(jaxtyping.Array, '')
dmean: jaxtyping.Float.(jaxtyping.Array, '')
class cryoblob.types.AdaptiveFilterConfig(*args, **kwargs)[source]

Bases: NamedTuple

PyTree for adaptive filtering parameters.

kernel_size

Size of the filter kernel

Type:

int

noise_estimate

Initial noise estimate

Type:

float

iterations

Number of adaptation iterations

Type:

int

kernel_size: jaxtyping.Int.(jaxtyping.Array, '')
noise_estimate: jaxtyping.Float.(jaxtyping.Array, '')
iterations: jaxtyping.Int.(jaxtyping.Array, '')
class cryoblob.types.RidgeDetectionConfig(*args, **kwargs)[source]

Bases: NamedTuple

PyTree for ridge detection parameters.

min_scale

Minimum scale for ridge detection

Type:

float

max_scale

Maximum scale for ridge detection

Type:

float

scale_step

Step size for scale space

Type:

float

threshold

Detection threshold

Type:

float

min_scale: jaxtyping.Float.(jaxtyping.Array, '')
max_scale: jaxtyping.Float.(jaxtyping.Array, '')
scale_step: jaxtyping.Float.(jaxtyping.Array, '')
threshold: jaxtyping.Float.(jaxtyping.Array, '')
class cryoblob.types.WatershedConfig(*args, **kwargs)[source]

Bases: NamedTuple

PyTree for watershed segmentation parameters.

min_distance

Minimum distance between markers

Type:

int

threshold_abs

Absolute threshold for markers (optional, use -1 for None)

Type:

float

compactness

Compactness parameter for watershed

Type:

float

min_distance: jaxtyping.Int.(jaxtyping.Array, '')
threshold_abs: jaxtyping.Float.(jaxtyping.Array, '')
compactness: jaxtyping.Float.(jaxtyping.Array, '')
class cryoblob.types.HessianBlobConfig(*args, **kwargs)[source]

Bases: NamedTuple

PyTree for Hessian-based blob detection.

min_sigma

Minimum sigma for scale space

Type:

float

max_sigma

Maximum sigma for scale space

Type:

float

num_sigma

Number of scales to test

Type:

int

threshold

Detection threshold

Type:

float

min_sigma: jaxtyping.Float.(jaxtyping.Array, '')
max_sigma: jaxtyping.Float.(jaxtyping.Array, '')
num_sigma: jaxtyping.Int.(jaxtyping.Array, '')
threshold: jaxtyping.Float.(jaxtyping.Array, '')
class cryoblob.types.EnhancedBlobDetectionConfig(*args, **kwargs)[source]

Bases: NamedTuple

PyTree for enhanced multi-method blob detection.

min_blob_size

Minimum expected blob size

Type:

float

max_blob_size

Maximum expected blob size

Type:

float

detection_threshold

Overall detection threshold

Type:

float

use_ridge_detection

Enable ridge detection for elongated objects

Type:

bool

use_watershed

Enable watershed for overlapping blobs

Type:

bool

min_blob_size: jaxtyping.Float.(jaxtyping.Array, '')
max_blob_size: jaxtyping.Float.(jaxtyping.Array, '')
detection_threshold: jaxtyping.Float.(jaxtyping.Array, '')
use_ridge_detection: jaxtyping.Bool.(jaxtyping.Array, '')
use_watershed: jaxtyping.Bool.(jaxtyping.Array, '')

Detection Method Guide

Method Selection

Blob Type

Recommended Method

Alternative Methods

Key Parameters

Circular

blob_list_log

hessian_blob_ detection

min_blob_size max_blob_size

Elongated (pill-shaped)

ridge_ detection

multi_scale_ridge_ detector

ridge_ threshold

Overlapping

watershed_ segmentation

enhanced_blob_ detection (full)

min_marker_ distance

Mixed/Complex

enhanced_blob_ detection

Factory functions from valid module

Use predefined configurations

Key Functions by Category

Basic Detection

  • blob_list_log() - Traditional LoG-based circular blob detection

  • preprocessing() - Image preprocessing pipeline

Enhanced Detection

  • enhanced_blob_detection() - Multi-method comprehensive detection

  • hessian_blob_detection() - Hessian-based blob detection with superior boundaries

  • ridge_detection() - Detect elongated objects using eigenvalue analysis

  • watershed_segmentation() - Separate overlapping structures

Configuration Factories

  • create_default_pipeline() - Standard detection configuration

  • create_elongated_objects_pipeline() - Optimized for elongated objects

  • create_overlapping_blobs_pipeline() - Optimized for overlapping structures

  • create_comprehensive_pipeline() - All methods enabled

Quick Usage Examples

Circular Blobs

blobs = cb.blob_list_log(mrc_image, min_blob_size=5, max_blob_size=20)

Elongated Objects

config = cb.create_elongated_objects_pipeline()
_, elongated, _ = cb.enhanced_blob_detection(mrc_image, **config.to_enhanced_kwargs())

Overlapping Structures

config = cb.create_overlapping_blobs_pipeline()
circular, _, separated = cb.enhanced_blob_detection(mrc_image, **config.to_enhanced_kwargs())

Comprehensive Analysis

config = cb.create_comprehensive_pipeline()
circular, elongated, overlapping = cb.enhanced_blob_detection(mrc_image, **config.to_enhanced_kwargs())