API reference

SegSpy’s public API is re-exported from SegSpy.__init__. The nine symbols below are all available via from SegSpy import ....

Configuration

class SegSpy.config.SegConfig(microscope_type='TEM', clahe_clip=3.0, clahe_tile=(8, 8), background_kernel=25, filter_type='bilateral', backend='traditional_cv', threshold_method='adaptive', min_area=100, use_grabcut_refinement=True, sam_model_type='vit_b', sam_checkpoint_path='', sam_device='auto', sam_points_per_side=32, sam_pred_iou_thresh=0.88, sam_stability_score_thresh=0.95, sam_min_area_ratio=0.0005, sam_max_area_ratio=0.6, sam_intensity_ratio=0.85, sam_edge_margin=5, compute_morphology=True, output_dir='output')[source]

Segmentation + morphology configuration.

All values default to sensible EM-image defaults; override via the constructor or from_signal().

Parameters:
  • microscope_type (str)

  • clahe_clip (float)

  • clahe_tile (tuple[int, int])

  • background_kernel (int)

  • filter_type (str)

  • backend (str)

  • threshold_method (str)

  • min_area (int)

  • use_grabcut_refinement (bool)

  • sam_model_type (str)

  • sam_checkpoint_path (str)

  • sam_device (str)

  • sam_points_per_side (int)

  • sam_pred_iou_thresh (float)

  • sam_stability_score_thresh (float)

  • sam_min_area_ratio (float)

  • sam_max_area_ratio (float)

  • sam_intensity_ratio (float)

  • sam_edge_margin (int)

  • compute_morphology (bool)

  • output_dir (str)

microscope_type: str = 'TEM'
clahe_clip: float = 3.0
clahe_tile: tuple[int, int] = (8, 8)
background_kernel: int = 25
filter_type: str = 'bilateral'
backend: str = 'traditional_cv'
threshold_method: str = 'adaptive'
min_area: int = 100
use_grabcut_refinement: bool = True
sam_model_type: str = 'vit_b'
sam_checkpoint_path: str = ''
sam_device: str = 'auto'
sam_points_per_side: int = 32
sam_pred_iou_thresh: float = 0.88
sam_stability_score_thresh: float = 0.95
sam_min_area_ratio: float = 0.0005
sam_max_area_ratio: float = 0.6
sam_intensity_ratio: float = 0.85
sam_edge_margin: int = 5
compute_morphology: bool = True
output_dir: str = 'output'
classmethod from_signal(signal, **overrides)[source]

Build a config, auto-detecting TEM/SEM from HyperSpy metadata.

Detection mirrors the EM community convention: a SEM block in Acquisition_instrument wins; otherwise TEM (the default). Any keyword overrides are applied on top of the defaults.

Data model

class SegSpy.core.ParticleObject(particle_id, image_roi, mask_roi, offset=(0, 0), bbox=(0, 0, 0, 0), area_px=0.0, metrics=<factory>)[source]

A single particle extracted from an EM image.

Carries the ROI image, its binary mask, bounding box, and a metrics dict populated by SegSpy.morphology.measure_morphology() (generic) and/or by downstream consumers (domain-specific, e.g. soot fractal dimension).

Parameters:
particle_id: int
image_roi: Any
mask_roi: Any
offset: tuple[int, int] = (0, 0)
bbox: tuple[int, int, int, int] = (0, 0, 0, 0)
area_px: float = 0.0
metrics: dict
add_metric(name, value)[source]

Record a named metric on this particle.

Parameters:
Return type:

None

get_physical_scale_nm()[source]

Return nm/pixel from the ROI’s calibration if available.

Reads the HyperSpy axis calibration when image_roi is a Signal2D; otherwise returns 1.0 (uncalibrated / numpy array).

Return type:

float

I/O helpers

SegSpy.io.to_uint8(signal)[source]

Normalize a signal’s data to uint8 (0–255) without mutating the input.

  • Already-uint8 signals are deep-copied unchanged.

  • Constant-valued signals map to all zeros (avoids divide-by-zero).

  • Everything else is linearly stretched to [0, 255].

Returns a new signal (deepcopy) whose .data is uint8.

SegSpy.io.get_scale_nm(signal)[source]

Return the nm-per-pixel scale from a signal’s axis calibration.

Reads the axis-0 scale and units and converts them to nanometres:

  • um → scale × 1000

  • nm → scale × 1

  • mm → scale × 1e6

  • pm → scale × 1e-3

Raises:

ValueError – if the units string is not a recognised length unit.

Return type:

float

Morphology

SegSpy.morphology.measure_morphology(obj, scale_nm=1.0)[source]

Compute particle-type-agnostic morphology metrics from obj.mask_roi.

The largest external contour of the mask is used. Results are written into obj.metrics and also returned. Length metrics are reported both in pixels (_px) and, where applicable, in nanometres (_nm = px × scale_nm).

Keys returned:

area_px, equivalent_diameter_px, equivalent_diameter_nm, feret_min_px, feret_max_px, feret_max_nm, perimeter_px, aspect_ratio, convexity, roundness, solidity, centroid_yx

Parameters:
Return type:

dict

Backends

class SegSpy.backends.base.SegmentationBackend[source]

Abstract base class for all segmentation algorithms.

abstractmethod segment(signal, config)[source]

Segment a signal and return a binary mask (0/255).

Parameters:
  • signal – HyperSpy Signal2D or numpy array containing the image.

  • config (SegConfig) – SegSpy configuration with segmentation parameters.

Returns:

Binary mask as a uint8 array with values 0 or 255.

Return type:

ndarray

classmethod supports(microscope_type, particle_type)[source]

Check if this backend supports the given microscope/particle combination.

Returns False by default. Subclasses override to opt-in. SegSpy’s built-in backends are particle-agnostic, so they return True.

Parameters:
  • microscope_type (str)

  • particle_type (str)

Return type:

bool

extract_objects(original_signal, mask, config)[source]

Extract individual particle objects from a binary mask.

Performs connected-component analysis and returns one ParticleObject per detected contour that clears config.min_area. Each object’s ROI/mask is sliced out of the original signal; when the input is a HyperSpy Signal2D the ROI is itself a calibrated signal (via isig), so downstream calibration works transparently.

Parameters:
Return type:

list[ParticleObject]

class SegSpy.backends.registry.SegmentationRegistry[source]

Class-level registry for managing available segmentation backends.

Backends are registered by their name class attribute and can be retrieved by name or auto-discovered via find_compatible().

classmethod register(backend_class)[source]

Register a segmentation backend class.

Raises:
  • TypeError – if backend_class is not a SegmentationBackend subclass.

  • ValueError – if its name is the default 'abstract' (i.e. unset), or if a different class is already registered under the same name.

Parameters:

backend_class (type[SegmentationBackend])

classmethod get(name)[source]

Instantiate and return a registered backend by name.

Raises:

ValueError – if no backend with the given name is registered.

Parameters:

name (str)

Return type:

SegmentationBackend

classmethod find_compatible(microscope_type, particle_type)[source]

Return the name of the first backend whose supports() is True.

Parameters:
  • microscope_type (str)

  • particle_type (str)

Return type:

str

classmethod list_backends()[source]

Return the names of all registered backends (in registration order).

Return type:

list[str]

classmethod clear()[source]

Remove all registered backends. Useful for test isolation.

class SegSpy.backends.traditional.TraditionalCVSegmenter[source]

CLAHE + morphology + threshold (+ GrabCut) segmentation.

classmethod supports(microscope_type, particle_type)[source]

Check if this backend supports the given microscope/particle combination.

Returns False by default. Subclasses override to opt-in. SegSpy’s built-in backends are particle-agnostic, so they return True.

Parameters:
  • microscope_type (str)

  • particle_type (str)

Return type:

bool

segment(signal, config)[source]

Segment a signal and return a binary mask (0/255).

Parameters:
  • signal – HyperSpy Signal2D or numpy array containing the image.

  • config (SegConfig) – SegSpy configuration with segmentation parameters.

Returns:

Binary mask as a uint8 array with values 0 or 255.

Return type:

ndarray

class SegSpy.backends.sam.SAMSegmenter[source]

SAM Auto-Mask Generator backend with 5-stage post-filtering.

classmethod supports(microscope_type, particle_type)[source]

Check if this backend supports the given microscope/particle combination.

Returns False by default. Subclasses override to opt-in. SegSpy’s built-in backends are particle-agnostic, so they return True.

Parameters:
  • microscope_type (str)

  • particle_type (str)

Return type:

bool

segment(signal, config)[source]

Segment a signal and return a binary mask (0/255).

Parameters:
  • signal – HyperSpy Signal2D or numpy array containing the image.

  • config (SegConfig) – SegSpy configuration with segmentation parameters.

Returns:

Binary mask as a uint8 array with values 0 or 255.

Return type:

ndarray