Tutorial: segment a DM4 image

This tutorial runs SegSpy as a library on a single DM4 image and prints a summary of the detected particles. It is the example shipped in the repository:

 1"""Minimal example: use SegSpy as a library (no CLI) on a DM4 image.
 2
 3Run with the path to any HyperSpy-readable EM image::
 4
 5    python examples/segment_dm4.py /path/to/image.dm4
 6"""
 7import sys
 8
 9import hyperspy.api as hs
10
11from SegSpy import SegConfig, SegmentationRegistry, get_scale_nm, measure_morphology
12
13
14def main(path: str) -> None:
15    signal = hs.load(path)
16    if isinstance(signal, list):
17        signal = signal[0]
18
19    config = SegConfig.from_signal(signal, min_area=100, use_grabcut_refinement=False)
20    scale_nm = get_scale_nm(signal)
21
22    backend = SegmentationRegistry.get(config.backend)
23    mask = backend.segment(signal, config)
24    objects = backend.extract_objects(signal, mask, config)
25
26    for obj in objects:
27        measure_morphology(obj, scale_nm=scale_nm)
28
29    print(f"{len(objects)} particle(s) found in {path}")
30    for obj in objects[:5]:
31        m = obj.metrics
32        print(
33            f"  #{obj.particle_id}: area={m['area_px']:.0f}px "
34            f"equiv_diam={m['equivalent_diameter_nm']:.1f}nm "
35            f"roundness={m['roundness']:.2f} solidity={m['solidity']:.2f}"
36        )
37    if len(objects) > 5:
38        print(f"  ... ({len(objects) - 5} more)")
39
40
41if __name__ == "__main__":
42    if len(sys.argv) != 2:
43        print(f"usage: {sys.argv[0]} <image>", file=sys.stderr)
44        sys.exit(2)
45    main(sys.argv[1])

Run it

python examples/segment_dm4.py /path/to/image.dm4

You’ll see a per-particle summary like:

12 particle(s) found in /path/to/image.dm4
  #1: area=312px equiv_diam=18.4nm roundness=0.71 solidity=0.94
  #2: area=205px equiv_diam=15.1nm roundness=0.83 solidity=0.97
  ...

Reading the metrics

measure_morphology writes these keys into each object’s metrics dict (length metrics are reported in pixels _px and nanometres _nm):

Key

Meaning

area_px

Contour area (px)

equivalent_diameter_px / equivalent_diameter_nm

Diameter of the equal-area circle

feret_min_px / feret_max_px / feret_max_nm

Min/max caliper (Feret) diameters

perimeter_px

Contour perimeter (px)

aspect_ratio

feret_max / feret_min

convexity

Convex-hull perimeter / contour perimeter

roundness

4·area / (π·feret_max²) (1 = circular)

solidity

area / convex-hull area (1 = convex)

centroid_yx

Moment-based centroid in (row, col)

To export every particle to CSV instead of printing, use the CLI, which writes the same metrics to <stem>_particles.csv.