Skip to content

Tracing a label mask

vertax.trace

Trace a segmentation label mask into a straight-edge vertex-model mesh.

This module turns a label mask — an integer image in which each cell carries a distinct positive label and unsegmented space carries 0 — into a polygonal mesh of the kind the rest of VertAX operates on: vertices at cell corners, edges along cell-cell interfaces, faces for cells.

It is written for the case a microscope actually produces: a crop. A crop is a patch of segmented cells surrounded by unsegmented margin, so some cells are cut by the field of view and some corners have a neighbour that was never imaged. Handling that honestly is the point of this module, and it is why trace_mask reports a boundary partition alongside the mesh rather than silently pretending the crop is a closed tissue.

Relation to vertax.mask_analysis

vertax.mask_analysis.find_vertices_edges_faces extracts a mesh from a mask that has been padded so every cell is fully enclosed. That assumption fails on a raw crop: there the Euler characteristic does not close (V - E + F != 0) and the extraction is not meaningful. Use vertax.mask_analysis for closed, padded masks; use this module for crops.

The corner lattice, and why there are no tuning parameters

The tracer works on the pixel-corner lattice of the mask — the grid of points at pixel corners, which is the exact dual of the segmentation. Corner (i, j) sits at image coordinate (x, y) = (j, i) and is surrounded by four pixels NW, NE, SW, SE. The four lattice segments meeting at a corner are boundary segments exactly when the two pixels they separate carry different labels, so the corner's boundary degree is

[NW != NE] + [SW != SE] + [NW != SW] + [NE != SE]     in {0, 2, 3, 4}

and degree >= 3 is the junction criterion. This is strictly more general than looking for three distinct labels in a 2x2 window: it also catches diagonal-touch trijunctions (4 segments, 3 labels) and checkerboard pinches (4 segments, 2 labels), which a 2x2-window test misses or mishandles.

From there the construction is forced, with no thresholds to choose:

  • 8-connected clusters of junction corners collapse to one vertex at their centroid, because a real trijunction is generally a small cluster of corners rather than a single one;
  • between two vertices the boundary is a chain of degree-2 corners carrying a single label pair, and each such chain becomes one straight edge (the underlying staircase polyline is retained only so the discarded length can be measured);
  • a face is the cycle of edges carrying one cell label. Background is not a face.

Straight edges are a modelling choice, not an approximation of convenience: drawing a cell-cell interface straight is the vertex-model convention, and the curvature it discards is precisely the pressure difference that inverse methods are trying to recover.

Free and clamped vertices

A vertex is clamped iff an unmodelled material — background, by default — is one of the labels meeting there. This is a force-balance criterion rather than a stylistic convention: at such a vertex at least one incident material is the environment that was never imaged, so force balance cannot be written from the data. Every other vertex is free and carries a complete force balance.

Consumers should write mechanical equations on TracedMesh.free rows only. Doing so has a consequence worth knowing in advance: restricting to those rows introduces exact null directions that are absent when all rows are used, so some cell-pressure combinations become unobservable. That is a property of the data being a crop, not of this tracer or of any particular boundary model.

The one parameter that does exist: rim_tol

A cell-cell interface is drawn straight on purpose. A cell-background arc is not an interface at all — it is the outer edge of the observed patch, i.e. a Dirichlet boundary condition read off the data — and there is no model reason to straighten it. Traced with a single chord per arc it is badly wrong, because a rim cell's whole outer side can be one junction-to-junction arc hundreds of pixels long; measured on real crops, rim-cell areas came out 22.6 % low in the median and 92 % low at worst.

Cell-background arcs are therefore subdivided by Ramer-Douglas-Peucker to rim_tol pixels, and the inserted break points are clamped vertices. This adds no free degree of freedom and no information, since every inserted vertex is clamped by construction (its label set is {0, cell}); it only stops the boundary condition from being wrong. Interior-cell areas are unaffected by it.

A cell is interior iff none of its edges is a cell-background edge, and rim-adjacent otherwise. Rim-adjacent cells are still complete, fully segmented cells — their outline against the background is a real membrane, not a truncation — so they keep their area term and contribute through their free vertices.

Typical use

from vertax.trace import regularize, trace_mask_closed, interior_area_ref, normalized

clean, report = regularize(mask)               # remove label debris; report says how much moved
assert report["frac_pixels_moved"] < 1e-3      # else investigate the segmentation
mesh = trace_mask_closed(clean, rim_tol=2.0)   # cells that fail to close become unmodelled
verts = normalized(mesh, interior_area_ref(mesh))   # lengths in units of sqrt(mean interior area)

Dependencies are numpy and scipy.ndimage only. Nothing here needs a mesh-reconstruction library, Cellpose, or JAX, so the tracer works on any label mask from any source.

TracedMesh dataclass

TracedMesh(stem: str, shape: tuple[int, int], verts: NDArray, vert_labels: list[frozenset], vert_cluster_size: NDArray, edges: NDArray, edge_labels: NDArray, edge_arc_len: NDArray, faces: list[list[int]], face_labels: NDArray, failures: dict, unmodelled: frozenset, junction_census: dict, diagnostics: dict = dict())

Straight-edge mesh traced from one label mask, in pixel units.

clamped property

clamped: NDArray

(Nv,) bool -- True where an unmodelled material is one of the incident labels.

edge_is_cell_cell property

edge_is_cell_cell: NDArray

True iff both flanking materials are modelled cells (a real interface).

face_is_interior property

face_is_interior: NDArray

A face is interior iff none of its edges borders an unmodelled material.

trace_mask

trace_mask(mask: NDArray, stem: str = '', rim_tol: float = 2.0, unmodelled: Iterable[int] = (0,)) -> TracedMesh

Trace one label mask into a straight-edge mesh.

Parameters:

Name Type Description Default
mask NDArray

integer label image, 0 for unsegmented space. Not modified.

required
stem str

optional identifier carried through onto the returned mesh, for reporting.

''
rim_tol float

Ramer-Douglas-Peucker tolerance in pixels, applied to clamped cell-background arcs only. Interior cell-cell interfaces are always single straight chords whatever this is set to, so rim_tol cannot affect an interior cell's area. See the module docstring for why the rim is treated differently and why this adds no free parameter.

2.0
unmodelled Iterable[int]

labels treated as missing environment. Background 0 is always included, whatever is passed. A cell whose outline does not close into a simple cycle — a segmentation topology defect, such as a region pinched to a point — must be added here and the trace repeated; the reason is the same one that clamps the background rim, that its mechanics cannot be written from the data, so every vertex it touches loses its force balance. trace_mask_closed performs that iteration automatically and is usually what you want.

(0,)

Returns:

Type Description
TracedMesh

A TracedMesh. Cells that failed to close are recorded in TracedMesh.failures and are not faces; this call does not raise on them.

Raises:

Type Description
AssertionError

if a lattice corner comes out with boundary degree 1, which is geometrically impossible and therefore means this tracer is wrong rather than that the mask is unusual.

trace_mask_closed

trace_mask_closed(mask: NDArray, stem: str = '', rim_tol: float = 2.0, max_rounds: int = 4) -> TracedMesh

Trace, then demote any cell whose outline did not close to unmodelled, and re-trace.

A cell that fails to close is a segmentation topology defect (e.g. a region pinched to a point, which is 8-connected but not simply connected as a polygon). It is handled exactly as the background is: it becomes missing environment, its vertices are clamped, and no tension is charged on its interfaces. It does not raise. The cumulative list of demoted cells is reported in mesh.diagnostics["failures_cumulative"] and their number in mesh.diagnostics["n_demoted_cells"]; if cells still fail to close after max_rounds rounds, mesh.diagnostics["unresolved"] is True and mesh.failures lists them.

vertex_degrees

vertex_degrees(m: TracedMesh) -> NDArray

Number of edges incident to each vertex of a traced mesh, as an integer array of length m.n_verts.

rasterize_face

rasterize_face(m: TracedMesh, k: int) -> tuple[NDArray, tuple[int, int, int, int]]

Boolean raster of face k over its bounding box, using pixel centres.

normalized

normalized(m: TracedMesh, a_ref: float) -> NDArray

Vertex coordinates in units of sqrt(A_ref), so that = 1 by construction.

interior_area_ref

interior_area_ref(m: TracedMesh) -> float

Reference cell area: the mean area of the interior (non-rim) faces of a traced mesh.

Falls back to the mean over all faces when the mesh has no interior face.

regularize

regularize(mask: NDArray) -> tuple[NDArray, dict]

Remove label debris from a segmentation mask, and report exactly how much was moved.

Automatic segmentation leaves pixel-level debris: a label may own stray one- or two-pixel islands disconnected from its main body. These are not tissue, and they matter here because they are topological rather than merely cosmetic. A stray island of label L sitting inside cell M creates a closed boundary loop; if that loop's junction corners fall into a single 8-connected cluster it collapses to a self-loop arc, which no straight-edge polygon can represent, and which can in turn break the outline of the cell that owns it.

The rule, and it is deliberately the weakest one that fixes the problem:

For every label, keep only its largest 8-connected component. Pixels in the smaller
components are reassigned to the label of the nearest surviving pixel, which may be
background.

Nothing else is touched -- no dilation, no erosion, no hole filling, no smoothing, no relabelling, no gap filling across the background margin. Anything more would be editing the data rather than making it representable.

Parameters:

Name Type Description Default
mask NDArray

integer label image; 0 is unsegmented space. Not modified.

required

Returns:

Type Description
tuple[NDArray, dict]

(clean, report). report carries n_labels_with_islands, n_pixels_moved, frac_pixels_moved and the per-label island sizes.

Note

report["frac_pixels_moved"] is not decoration — check it. It should be negligible (order 1e-4 or below on a good segmentation). If it is not, that is a finding about the segmentation and should be investigated, not a licence to clean harder.