micro_sam.v2.postprocessing

Post-processing for UniSAM2 automatic segmentation predictions.

Converts the model's raw outputs (foreground probability + directed distance channels) into instance segmentation maps. Two strategies are provided:

  • flow_instance_segmentation: CellPose-style flow following. Suitable for LM data (2D and 3D).
  • run_multicut: Slice-wise oversegmentation + graph multicut. Suitable for EM data with large, densely-packed objects (3D only).
  1"""Post-processing for UniSAM2 automatic segmentation predictions.
  2
  3Converts the model's raw outputs (foreground probability + directed distance channels)
  4into instance segmentation maps. Two strategies are provided:
  5
  6- ``flow_instance_segmentation``: CellPose-style flow following. Suitable for LM data
  7  (2D and 3D).
  8- ``run_multicut``: Slice-wise oversegmentation + graph multicut. Suitable for EM data
  9  with large, densely-packed objects (3D only).
 10"""
 11
 12from concurrent import futures
 13from typing import Optional, Tuple
 14
 15import numpy as np
 16from tqdm import tqdm
 17
 18from bioimage_cpp.flow import compute_flow_density
 19from bioimage_cpp.segmentation import label, watershed
 20
 21from .util import DEFAULT_MODEL, parameter_family
 22from .._model_settings import DEFAULT_POSTPROCESSING
 23
 24
 25def default_postprocessing(model_type: str = DEFAULT_MODEL, mode: str = "sparse", is_volume: bool = False) -> dict:
 26    """The default postprocessing parameters for one model, mode and dimensionality.
 27
 28    Args:
 29        model_type: The model, e.g. 'hvit_t_cells' or 'hvit_s_em_mito', or a SAM2 backbone, e.g. 'hvit_t', which
 30            uses the 'cells' defaults. Its family and backbone select the table, see `parameter_family`.
 31        mode: 'sparse' (`flow_instance_segmentation`) or 'dense' (`run_multicut`).
 32        is_volume: Whether to use the '3d' table of the 'sparse' mode instead of the '2d' one. The 'dense'
 33            mode has one table for both.
 34
 35    Returns:
 36        The default parameter dict for that model, mode and dimensionality.
 37    """
 38    family, backbone = parameter_family(model_type), model_type[:6]
 39    params = DEFAULT_POSTPROCESSING.get(family, {}).get(backbone, {}).get(mode)
 40    if params is None:
 41        raise ValueError(
 42            f"No default {mode} postprocessing parameters for model type '{model_type}'. They exist for "
 43            + ", ".join(
 44                f"{family_name}: {sorted(b for b, modes in table.items() if mode in modes)}"
 45                for family_name, table in DEFAULT_POSTPROCESSING.items()
 46            ) + "."
 47        )
 48    return params["3d" if is_volume else "2d"] if mode == "sparse" else params
 49
 50
 51def _compute_flow_density(
 52    directed_distances: np.ndarray,
 53    fg_mask: np.ndarray,
 54    n_iter: int = 100,
 55    dt: float = 0.5,
 56    sigma: float = 1.0,
 57    spacing: Optional[Tuple] = None,
 58    n_threads: int = 8,
 59) -> np.ndarray:
 60    """Integrate a flow field and return a convergence-density map.
 61
 62    Pixels in the foreground are advected along the (negated) directed-distance
 63    field. The density of where they converge gives one peak per object, which is
 64    used downstream as seeds for a seeded watershed.
 65
 66    Args:
 67        directed_distances: Distance channels stacked along axis 0,
 68            shape (ndim, *spatial).
 69        fg_mask: Boolean foreground mask, shape (*spatial).
 70        n_iter: Number of integration steps.
 71        dt: Step size per integration step.
 72        sigma: Gaussian smoothing sigma applied to the density map.
 73        spacing: Anisotropic voxel spacing for 3D data, e.g. (4, 1, 1).
 74            Used for physically-isotropic Gaussian smoothing.
 75        n_threads: Number of threads for ``bioimage_cpp.flow.compute_flow_density``.
 76
 77    Returns:
 78        Smoothed convergence-density map, same spatial shape as fg_mask.
 79    """
 80    return compute_flow_density(
 81        -directed_distances, fg_mask,
 82        n_iter=n_iter, dt=dt, sigma=sigma, spacing=spacing, number_of_threads=n_threads,
 83    )
 84
 85
 86def watershed_heightmap(
 87    foreground: np.ndarray, directed_distances: np.ndarray, foreground_weight: float
 88) -> np.ndarray:
 89    """Build the heightmap that separates touching objects in the seeded watershed.
 90
 91    The inverted distance magnitude puts object boundaries at its local minima, which is a weak edge
 92    signal. The foreground probability carries the actual object edge, so mixing the two in sharpens
 93    the boundaries. Both terms are scaled to [0, 1] to make the weight meaningful.
 94
 95    Args:
 96        foreground: Foreground probability map, shape (*spatial).
 97        directed_distances: Distance channels stacked along axis 0, shape (ndim, *spatial).
 98        foreground_weight: Weight of the foreground term. 0 uses the distances only.
 99
100    Returns:
101        The watershed heightmap, float32 array of the same spatial shape as foreground.
102    """
103    distances = np.linalg.norm(directed_distances, axis=0)
104    distances = distances.max() - distances
105    distances /= (distances.max() + 1e-9)
106    hmap = foreground_weight * (1.0 - np.clip(foreground, 0, 1)) + (1.0 - foreground_weight) * distances
107    return np.ascontiguousarray(hmap, dtype="float32")
108
109
110def flow_instance_segmentation(
111    foreground: np.ndarray,
112    directed_distances: np.ndarray,
113    model_type: str = DEFAULT_MODEL,
114    foreground_threshold: Optional[float] = None,
115    n_iter: Optional[int] = None,
116    dt: Optional[float] = None,
117    sigma: Optional[float] = None,
118    spacing: Optional[Tuple] = None,
119    density_threshold: Optional[float] = None,
120    min_size: Optional[int] = None,
121    foreground_weight: Optional[float] = None,
122    n_threads: int = 8,
123    boundary: Optional[np.ndarray] = None,
124    boundary_weight: Optional[float] = None,
125    boundary_mask_threshold: Optional[float] = None,
126) -> np.ndarray:
127    """Instance segmentation from directed-distance predictions via flow following.
128
129    Integrates a CellPose-style flow field derived from the directed distances,
130    extracts convergence-density seeds, and finalises instances with a seeded
131    watershed. Works for both 2D and 3D inputs.
132
133    If 3 distance channels are supplied for a 2D foreground map the leading
134    z-channel is automatically dropped, so you can always pass the three distance
135    channels ``out[1:4]`` regardless of dimensionality. Any other channel count raises,
136    so that an auxiliary channel appended to the prediction is never read as a distance.
137
138    Args:
139        foreground: Foreground probability map, shape (Y, X) or (Z, Y, X).
140        directed_distances: Distance channels stacked along axis 0,
141            shape (ndim, *spatial) or (3, *spatial) for 2D input.
142        model_type: The SAM2 backbone the predictions came from, e.g. 'hvit_t'. Selects the default
143            for any of the tunable parameters below left as None, see `default_postprocessing`.
144        foreground_threshold: Foreground binarisation threshold.
145        n_iter: Number of flow-integration steps.
146        dt: Integration step size.
147        sigma: Gaussian sigma for smoothing the convergence-density map.
148        spacing: Anisotropic voxel spacing for 3D inputs, e.g. (4, 1, 1).
149        density_threshold: Convergence-density threshold for seed extraction.
150        min_size: Minimum object size (pixels/voxels) to keep.
151        foreground_weight: Weight of the foreground term in the watershed heightmap, see
152            `watershed_heightmap`.
153        n_threads: Number of threads for the flow computation.
154        boundary: The predicted object-boundary probability (channel 4 of the UniSAM2 prediction), same shape as
155            the foreground. Only used through the two keywords below.
156        boundary_weight: Adds ``boundary_weight * boundary`` to the watershed height map, so that the fronts of
157            two touching objects meet on the predicted boundary. None or 0 leaves the height map unchanged.
158        boundary_mask_threshold: Excludes the pixels with ``boundary > threshold`` from the first seeded watershed
159            and assigns them afterwards by flooding from the resulting instances, so that no instance grows
160            across a predicted boundary. None disables the exclusion.
161
162    Returns:
163        Instance segmentation, uint32 array, same spatial shape as foreground.
164    """
165    defaults = default_postprocessing(model_type, "sparse", is_volume=foreground.ndim == 3)
166    if foreground_threshold is None:
167        foreground_threshold = defaults["foreground_threshold"]
168    if n_iter is None:
169        n_iter = defaults["n_iter"]
170    if dt is None:
171        dt = defaults["dt"]
172    if sigma is None:
173        sigma = defaults["sigma"]
174    if density_threshold is None:
175        density_threshold = defaults["density_threshold"]
176    if min_size is None:
177        min_size = defaults["min_size"]
178    if foreground_weight is None:
179        foreground_weight = defaults["foreground_weight"]
180
181    ndim = foreground.ndim
182    if directed_distances.shape[0] == 3 and ndim == 2:
183        directed_distances = directed_distances[1:]  # Drop the (pseudo) z channel of a 2d prediction.
184    if directed_distances.shape[0] != ndim:
185        raise ValueError(
186            f"Expected {ndim} distance channels (or 3 for 2d input), got {directed_distances.shape[0]}. Pass the "
187            "three distance channels 'prediction[1:4]'; the boundary channel goes into 'boundary'."
188        )
189    if boundary is None and (boundary_weight is not None or boundary_mask_threshold is not None):
190        raise ValueError("'boundary_weight' and 'boundary_mask_threshold' need the predicted boundary map.")
191    if boundary is not None and boundary.shape != foreground.shape:
192        raise ValueError(f"The boundary map {boundary.shape} must have the shape of the foreground {foreground.shape}.")
193
194    fg_mask = foreground > foreground_threshold
195
196    density = _compute_flow_density(
197        directed_distances, fg_mask, n_iter=n_iter, dt=dt, sigma=sigma, spacing=spacing, n_threads=n_threads,
198    )
199
200    seeds = label(density > density_threshold)
201    hmap = watershed_heightmap(foreground, directed_distances, foreground_weight)
202    if boundary is not None and boundary_weight is not None and boundary_weight != 0:
203        # The predicted boundary becomes a ridge, so the fronts of two touching objects meet on it.
204        hmap = np.ascontiguousarray(hmap + np.float32(boundary_weight) * np.clip(boundary, 0, 1), dtype="float32")
205    if boundary is not None and boundary_mask_threshold is not None:
206        # Flood everything but the boundary pixels first, then let the instances claim the boundary pixels.
207        open_mask = fg_mask & ~(boundary > boundary_mask_threshold)
208        first = watershed(hmap, markers=np.where(open_mask, seeds, 0).astype(seeds.dtype), mask=open_mask)
209        seg = watershed(hmap, markers=first, mask=fg_mask)
210    else:
211        seg = watershed(hmap, markers=seeds, mask=fg_mask)
212
213    if min_size > 0:
214        ids, sizes = np.unique(seg, return_counts=True)
215        discard = ids[(sizes < min_size) & (ids > 0)]
216        seg[np.isin(seg, discard)] = 0
217        seg = watershed(hmap, markers=seg, mask=fg_mask)
218
219    return seg.astype("uint32")
220
221
222def run_multicut(
223    boundary_map: np.ndarray,
224    distances: np.ndarray,
225    model_type: str = DEFAULT_MODEL,
226    beta: Optional[float] = None,
227    density_threshold: Optional[float] = None,
228    n_iter: Optional[int] = None,
229    dt: Optional[float] = None,
230    sigma: Optional[float] = None,
231    n_threads: int = 8,
232) -> np.ndarray:
233    """Instance segmentation for 3D EM data via slice-wise oversegmentation + multicut.
234
235    For each z-slice a convergence-density seeded watershed produces an
236    oversegmentation. A region-adjacency graph is then lifted across all
237    slices and a multicut optimisation yields the final 3D instances.
238
239    Args:
240        boundary_map: Boundary probability map, shape (Z, Y, X).
241            Typically ``1 - foreground`` or ``fg.max() - fg``.
242        distances: In-plane distance channels (ydist, xdist), shape (2, Z, Y, X).
243        model_type: The SAM2 backbone the predictions came from, e.g. 'hvit_t'. Selects the default
244            for any of the tunable parameters below left as None, see `default_postprocessing`.
245        beta: Multicut boundary bias; higher values favour more merging.
246        density_threshold: Convergence-density threshold for seed extraction
247            in the slice-wise oversegmentation.
248        n_iter: Flow integration steps for the oversegmentation seeding.
249        dt: Flow integration step size.
250        sigma: Gaussian sigma for smoothing the convergence-density map.
251        n_threads: Number of threads for the parallel slice-wise oversegmentation.
252
253    Returns:
254        Instance segmentation, uint64 array, shape (Z, Y, X).
255    """
256    defaults = default_postprocessing(model_type, "dense")
257    if beta is None:
258        beta = defaults["beta"]
259    if density_threshold is None:
260        density_threshold = defaults["density_threshold"]
261    if n_iter is None:
262        n_iter = defaults["n_iter"]
263    if dt is None:
264        dt = defaults["dt"]
265    if sigma is None:
266        sigma = defaults["sigma"]
267
268    from elf.segmentation.features import (
269        compute_rag, compute_boundary_mean_and_length,
270        compute_z_edge_mask, project_node_labels_to_pixels,
271    )
272    from elf.segmentation.multicut import compute_edge_costs, multicut_decomposition
273
274    n_slices = boundary_map.shape[0]
275    overseg = np.zeros(boundary_map.shape, dtype="uint64")
276
277    def _run_overseg(z):
278        bd = boundary_map[z]
279        dists = distances[:, z]
280        fg_mask = np.ones(bd.shape, dtype="bool")
281        # 1 thread per slice: the ThreadPoolExecutor above already parallelizes across slices, so a
282        # higher value here would oversubscribe instead of adding throughput.
283        density = _compute_flow_density(dists, fg_mask, n_iter=n_iter, dt=dt, sigma=sigma, n_threads=1)
284        seeds = label(density > density_threshold)
285        # A slice without seeds becomes one region, else the z offset turns its zeros into the previous slice's last id.
286        if seeds.max() == 0:
287            seeds = np.ones(bd.shape, dtype=seeds.dtype)
288        # watershed requires a float heightmap. Boundary maps are usually float already.
289        bd = bd if np.issubdtype(bd.dtype, np.floating) else bd.astype("float32")
290        wsz = watershed(bd, markers=seeds)
291        overseg[z] = wsz
292        return int(wsz.max())
293
294    with futures.ThreadPoolExecutor(n_threads) as tp:
295        offsets = list(tqdm(
296            tp.map(_run_overseg, range(n_slices)),
297            total=n_slices, desc="Slice-wise oversegmentation",
298        ))
299
300    offsets = np.array(offsets, dtype="uint64")
301    offsets = np.roll(offsets, 1)
302    offsets[0] = 0
303    overseg += np.cumsum(offsets)[:, None, None]
304
305    rag = compute_rag(overseg)
306    if rag.numberOfEdges == 0:  # A single region leaves nothing to merge.
307        return overseg.astype("uint64")
308
309    feats = compute_boundary_mean_and_length(rag, overseg, boundary_map)
310    z_edges = None if n_slices == 1 else compute_z_edge_mask(rag, overseg)
311    # 'xyz' weights in-plane and z edges as separate populations, so it needs both to be present.
312    if z_edges is None or z_edges.all() or not z_edges.any():
313        costs = compute_edge_costs(feats[:, 0], edge_sizes=feats[:, 1], weighting_scheme="all", beta=beta)
314    else:
315        costs = compute_edge_costs(
316            feats[:, 0], edge_sizes=feats[:, 1],
317            weighting_scheme="xyz", z_edge_mask=z_edges, beta=beta,
318        )
319    node_labels = multicut_decomposition(rag, costs)
320    seg = project_node_labels_to_pixels(rag, overseg, node_labels)
321
322    return seg.astype("uint64")
def default_postprocessing( model_type: str = 'hvit_t_cells', mode: str = 'sparse', is_volume: bool = False) -> dict:
26def default_postprocessing(model_type: str = DEFAULT_MODEL, mode: str = "sparse", is_volume: bool = False) -> dict:
27    """The default postprocessing parameters for one model, mode and dimensionality.
28
29    Args:
30        model_type: The model, e.g. 'hvit_t_cells' or 'hvit_s_em_mito', or a SAM2 backbone, e.g. 'hvit_t', which
31            uses the 'cells' defaults. Its family and backbone select the table, see `parameter_family`.
32        mode: 'sparse' (`flow_instance_segmentation`) or 'dense' (`run_multicut`).
33        is_volume: Whether to use the '3d' table of the 'sparse' mode instead of the '2d' one. The 'dense'
34            mode has one table for both.
35
36    Returns:
37        The default parameter dict for that model, mode and dimensionality.
38    """
39    family, backbone = parameter_family(model_type), model_type[:6]
40    params = DEFAULT_POSTPROCESSING.get(family, {}).get(backbone, {}).get(mode)
41    if params is None:
42        raise ValueError(
43            f"No default {mode} postprocessing parameters for model type '{model_type}'. They exist for "
44            + ", ".join(
45                f"{family_name}: {sorted(b for b, modes in table.items() if mode in modes)}"
46                for family_name, table in DEFAULT_POSTPROCESSING.items()
47            ) + "."
48        )
49    return params["3d" if is_volume else "2d"] if mode == "sparse" else params

The default postprocessing parameters for one model, mode and dimensionality.

Arguments:
  • model_type: The model, e.g. 'hvit_t_cells' or 'hvit_s_em_mito', or a SAM2 backbone, e.g. 'hvit_t', which uses the 'cells' defaults. Its family and backbone select the table, see parameter_family.
  • mode: 'sparse' (flow_instance_segmentation) or 'dense' (run_multicut).
  • is_volume: Whether to use the '3d' table of the 'sparse' mode instead of the '2d' one. The 'dense' mode has one table for both.
Returns:

The default parameter dict for that model, mode and dimensionality.

def watershed_heightmap( foreground: numpy.ndarray, directed_distances: numpy.ndarray, foreground_weight: float) -> numpy.ndarray:
 87def watershed_heightmap(
 88    foreground: np.ndarray, directed_distances: np.ndarray, foreground_weight: float
 89) -> np.ndarray:
 90    """Build the heightmap that separates touching objects in the seeded watershed.
 91
 92    The inverted distance magnitude puts object boundaries at its local minima, which is a weak edge
 93    signal. The foreground probability carries the actual object edge, so mixing the two in sharpens
 94    the boundaries. Both terms are scaled to [0, 1] to make the weight meaningful.
 95
 96    Args:
 97        foreground: Foreground probability map, shape (*spatial).
 98        directed_distances: Distance channels stacked along axis 0, shape (ndim, *spatial).
 99        foreground_weight: Weight of the foreground term. 0 uses the distances only.
100
101    Returns:
102        The watershed heightmap, float32 array of the same spatial shape as foreground.
103    """
104    distances = np.linalg.norm(directed_distances, axis=0)
105    distances = distances.max() - distances
106    distances /= (distances.max() + 1e-9)
107    hmap = foreground_weight * (1.0 - np.clip(foreground, 0, 1)) + (1.0 - foreground_weight) * distances
108    return np.ascontiguousarray(hmap, dtype="float32")

Build the heightmap that separates touching objects in the seeded watershed.

The inverted distance magnitude puts object boundaries at its local minima, which is a weak edge signal. The foreground probability carries the actual object edge, so mixing the two in sharpens the boundaries. Both terms are scaled to [0, 1] to make the weight meaningful.

Arguments:
  • foreground: Foreground probability map, shape (*spatial).
  • directed_distances: Distance channels stacked along axis 0, shape (ndim, *spatial).
  • foreground_weight: Weight of the foreground term. 0 uses the distances only.
Returns:

The watershed heightmap, float32 array of the same spatial shape as foreground.

def flow_instance_segmentation( foreground: numpy.ndarray, directed_distances: numpy.ndarray, model_type: str = 'hvit_t_cells', foreground_threshold: Optional[float] = None, n_iter: Optional[int] = None, dt: Optional[float] = None, sigma: Optional[float] = None, spacing: Optional[Tuple] = None, density_threshold: Optional[float] = None, min_size: Optional[int] = None, foreground_weight: Optional[float] = None, n_threads: int = 8, boundary: Optional[numpy.ndarray] = None, boundary_weight: Optional[float] = None, boundary_mask_threshold: Optional[float] = None) -> numpy.ndarray:
111def flow_instance_segmentation(
112    foreground: np.ndarray,
113    directed_distances: np.ndarray,
114    model_type: str = DEFAULT_MODEL,
115    foreground_threshold: Optional[float] = None,
116    n_iter: Optional[int] = None,
117    dt: Optional[float] = None,
118    sigma: Optional[float] = None,
119    spacing: Optional[Tuple] = None,
120    density_threshold: Optional[float] = None,
121    min_size: Optional[int] = None,
122    foreground_weight: Optional[float] = None,
123    n_threads: int = 8,
124    boundary: Optional[np.ndarray] = None,
125    boundary_weight: Optional[float] = None,
126    boundary_mask_threshold: Optional[float] = None,
127) -> np.ndarray:
128    """Instance segmentation from directed-distance predictions via flow following.
129
130    Integrates a CellPose-style flow field derived from the directed distances,
131    extracts convergence-density seeds, and finalises instances with a seeded
132    watershed. Works for both 2D and 3D inputs.
133
134    If 3 distance channels are supplied for a 2D foreground map the leading
135    z-channel is automatically dropped, so you can always pass the three distance
136    channels ``out[1:4]`` regardless of dimensionality. Any other channel count raises,
137    so that an auxiliary channel appended to the prediction is never read as a distance.
138
139    Args:
140        foreground: Foreground probability map, shape (Y, X) or (Z, Y, X).
141        directed_distances: Distance channels stacked along axis 0,
142            shape (ndim, *spatial) or (3, *spatial) for 2D input.
143        model_type: The SAM2 backbone the predictions came from, e.g. 'hvit_t'. Selects the default
144            for any of the tunable parameters below left as None, see `default_postprocessing`.
145        foreground_threshold: Foreground binarisation threshold.
146        n_iter: Number of flow-integration steps.
147        dt: Integration step size.
148        sigma: Gaussian sigma for smoothing the convergence-density map.
149        spacing: Anisotropic voxel spacing for 3D inputs, e.g. (4, 1, 1).
150        density_threshold: Convergence-density threshold for seed extraction.
151        min_size: Minimum object size (pixels/voxels) to keep.
152        foreground_weight: Weight of the foreground term in the watershed heightmap, see
153            `watershed_heightmap`.
154        n_threads: Number of threads for the flow computation.
155        boundary: The predicted object-boundary probability (channel 4 of the UniSAM2 prediction), same shape as
156            the foreground. Only used through the two keywords below.
157        boundary_weight: Adds ``boundary_weight * boundary`` to the watershed height map, so that the fronts of
158            two touching objects meet on the predicted boundary. None or 0 leaves the height map unchanged.
159        boundary_mask_threshold: Excludes the pixels with ``boundary > threshold`` from the first seeded watershed
160            and assigns them afterwards by flooding from the resulting instances, so that no instance grows
161            across a predicted boundary. None disables the exclusion.
162
163    Returns:
164        Instance segmentation, uint32 array, same spatial shape as foreground.
165    """
166    defaults = default_postprocessing(model_type, "sparse", is_volume=foreground.ndim == 3)
167    if foreground_threshold is None:
168        foreground_threshold = defaults["foreground_threshold"]
169    if n_iter is None:
170        n_iter = defaults["n_iter"]
171    if dt is None:
172        dt = defaults["dt"]
173    if sigma is None:
174        sigma = defaults["sigma"]
175    if density_threshold is None:
176        density_threshold = defaults["density_threshold"]
177    if min_size is None:
178        min_size = defaults["min_size"]
179    if foreground_weight is None:
180        foreground_weight = defaults["foreground_weight"]
181
182    ndim = foreground.ndim
183    if directed_distances.shape[0] == 3 and ndim == 2:
184        directed_distances = directed_distances[1:]  # Drop the (pseudo) z channel of a 2d prediction.
185    if directed_distances.shape[0] != ndim:
186        raise ValueError(
187            f"Expected {ndim} distance channels (or 3 for 2d input), got {directed_distances.shape[0]}. Pass the "
188            "three distance channels 'prediction[1:4]'; the boundary channel goes into 'boundary'."
189        )
190    if boundary is None and (boundary_weight is not None or boundary_mask_threshold is not None):
191        raise ValueError("'boundary_weight' and 'boundary_mask_threshold' need the predicted boundary map.")
192    if boundary is not None and boundary.shape != foreground.shape:
193        raise ValueError(f"The boundary map {boundary.shape} must have the shape of the foreground {foreground.shape}.")
194
195    fg_mask = foreground > foreground_threshold
196
197    density = _compute_flow_density(
198        directed_distances, fg_mask, n_iter=n_iter, dt=dt, sigma=sigma, spacing=spacing, n_threads=n_threads,
199    )
200
201    seeds = label(density > density_threshold)
202    hmap = watershed_heightmap(foreground, directed_distances, foreground_weight)
203    if boundary is not None and boundary_weight is not None and boundary_weight != 0:
204        # The predicted boundary becomes a ridge, so the fronts of two touching objects meet on it.
205        hmap = np.ascontiguousarray(hmap + np.float32(boundary_weight) * np.clip(boundary, 0, 1), dtype="float32")
206    if boundary is not None and boundary_mask_threshold is not None:
207        # Flood everything but the boundary pixels first, then let the instances claim the boundary pixels.
208        open_mask = fg_mask & ~(boundary > boundary_mask_threshold)
209        first = watershed(hmap, markers=np.where(open_mask, seeds, 0).astype(seeds.dtype), mask=open_mask)
210        seg = watershed(hmap, markers=first, mask=fg_mask)
211    else:
212        seg = watershed(hmap, markers=seeds, mask=fg_mask)
213
214    if min_size > 0:
215        ids, sizes = np.unique(seg, return_counts=True)
216        discard = ids[(sizes < min_size) & (ids > 0)]
217        seg[np.isin(seg, discard)] = 0
218        seg = watershed(hmap, markers=seg, mask=fg_mask)
219
220    return seg.astype("uint32")

Instance segmentation from directed-distance predictions via flow following.

Integrates a CellPose-style flow field derived from the directed distances, extracts convergence-density seeds, and finalises instances with a seeded watershed. Works for both 2D and 3D inputs.

If 3 distance channels are supplied for a 2D foreground map the leading z-channel is automatically dropped, so you can always pass the three distance channels out[1:4] regardless of dimensionality. Any other channel count raises, so that an auxiliary channel appended to the prediction is never read as a distance.

Arguments:
  • foreground: Foreground probability map, shape (Y, X) or (Z, Y, X).
  • directed_distances: Distance channels stacked along axis 0, shape (ndim, *spatial) or (3, *spatial) for 2D input.
  • model_type: The SAM2 backbone the predictions came from, e.g. 'hvit_t'. Selects the default for any of the tunable parameters below left as None, see default_postprocessing.
  • foreground_threshold: Foreground binarisation threshold.
  • n_iter: Number of flow-integration steps.
  • dt: Integration step size.
  • sigma: Gaussian sigma for smoothing the convergence-density map.
  • spacing: Anisotropic voxel spacing for 3D inputs, e.g. (4, 1, 1).
  • density_threshold: Convergence-density threshold for seed extraction.
  • min_size: Minimum object size (pixels/voxels) to keep.
  • foreground_weight: Weight of the foreground term in the watershed heightmap, see watershed_heightmap.
  • n_threads: Number of threads for the flow computation.
  • boundary: The predicted object-boundary probability (channel 4 of the UniSAM2 prediction), same shape as the foreground. Only used through the two keywords below.
  • boundary_weight: Adds boundary_weight * boundary to the watershed height map, so that the fronts of two touching objects meet on the predicted boundary. None or 0 leaves the height map unchanged.
  • boundary_mask_threshold: Excludes the pixels with boundary > threshold from the first seeded watershed and assigns them afterwards by flooding from the resulting instances, so that no instance grows across a predicted boundary. None disables the exclusion.
Returns:

Instance segmentation, uint32 array, same spatial shape as foreground.

def run_multicut( boundary_map: numpy.ndarray, distances: numpy.ndarray, model_type: str = 'hvit_t_cells', beta: Optional[float] = None, density_threshold: Optional[float] = None, n_iter: Optional[int] = None, dt: Optional[float] = None, sigma: Optional[float] = None, n_threads: int = 8) -> numpy.ndarray:
223def run_multicut(
224    boundary_map: np.ndarray,
225    distances: np.ndarray,
226    model_type: str = DEFAULT_MODEL,
227    beta: Optional[float] = None,
228    density_threshold: Optional[float] = None,
229    n_iter: Optional[int] = None,
230    dt: Optional[float] = None,
231    sigma: Optional[float] = None,
232    n_threads: int = 8,
233) -> np.ndarray:
234    """Instance segmentation for 3D EM data via slice-wise oversegmentation + multicut.
235
236    For each z-slice a convergence-density seeded watershed produces an
237    oversegmentation. A region-adjacency graph is then lifted across all
238    slices and a multicut optimisation yields the final 3D instances.
239
240    Args:
241        boundary_map: Boundary probability map, shape (Z, Y, X).
242            Typically ``1 - foreground`` or ``fg.max() - fg``.
243        distances: In-plane distance channels (ydist, xdist), shape (2, Z, Y, X).
244        model_type: The SAM2 backbone the predictions came from, e.g. 'hvit_t'. Selects the default
245            for any of the tunable parameters below left as None, see `default_postprocessing`.
246        beta: Multicut boundary bias; higher values favour more merging.
247        density_threshold: Convergence-density threshold for seed extraction
248            in the slice-wise oversegmentation.
249        n_iter: Flow integration steps for the oversegmentation seeding.
250        dt: Flow integration step size.
251        sigma: Gaussian sigma for smoothing the convergence-density map.
252        n_threads: Number of threads for the parallel slice-wise oversegmentation.
253
254    Returns:
255        Instance segmentation, uint64 array, shape (Z, Y, X).
256    """
257    defaults = default_postprocessing(model_type, "dense")
258    if beta is None:
259        beta = defaults["beta"]
260    if density_threshold is None:
261        density_threshold = defaults["density_threshold"]
262    if n_iter is None:
263        n_iter = defaults["n_iter"]
264    if dt is None:
265        dt = defaults["dt"]
266    if sigma is None:
267        sigma = defaults["sigma"]
268
269    from elf.segmentation.features import (
270        compute_rag, compute_boundary_mean_and_length,
271        compute_z_edge_mask, project_node_labels_to_pixels,
272    )
273    from elf.segmentation.multicut import compute_edge_costs, multicut_decomposition
274
275    n_slices = boundary_map.shape[0]
276    overseg = np.zeros(boundary_map.shape, dtype="uint64")
277
278    def _run_overseg(z):
279        bd = boundary_map[z]
280        dists = distances[:, z]
281        fg_mask = np.ones(bd.shape, dtype="bool")
282        # 1 thread per slice: the ThreadPoolExecutor above already parallelizes across slices, so a
283        # higher value here would oversubscribe instead of adding throughput.
284        density = _compute_flow_density(dists, fg_mask, n_iter=n_iter, dt=dt, sigma=sigma, n_threads=1)
285        seeds = label(density > density_threshold)
286        # A slice without seeds becomes one region, else the z offset turns its zeros into the previous slice's last id.
287        if seeds.max() == 0:
288            seeds = np.ones(bd.shape, dtype=seeds.dtype)
289        # watershed requires a float heightmap. Boundary maps are usually float already.
290        bd = bd if np.issubdtype(bd.dtype, np.floating) else bd.astype("float32")
291        wsz = watershed(bd, markers=seeds)
292        overseg[z] = wsz
293        return int(wsz.max())
294
295    with futures.ThreadPoolExecutor(n_threads) as tp:
296        offsets = list(tqdm(
297            tp.map(_run_overseg, range(n_slices)),
298            total=n_slices, desc="Slice-wise oversegmentation",
299        ))
300
301    offsets = np.array(offsets, dtype="uint64")
302    offsets = np.roll(offsets, 1)
303    offsets[0] = 0
304    overseg += np.cumsum(offsets)[:, None, None]
305
306    rag = compute_rag(overseg)
307    if rag.numberOfEdges == 0:  # A single region leaves nothing to merge.
308        return overseg.astype("uint64")
309
310    feats = compute_boundary_mean_and_length(rag, overseg, boundary_map)
311    z_edges = None if n_slices == 1 else compute_z_edge_mask(rag, overseg)
312    # 'xyz' weights in-plane and z edges as separate populations, so it needs both to be present.
313    if z_edges is None or z_edges.all() or not z_edges.any():
314        costs = compute_edge_costs(feats[:, 0], edge_sizes=feats[:, 1], weighting_scheme="all", beta=beta)
315    else:
316        costs = compute_edge_costs(
317            feats[:, 0], edge_sizes=feats[:, 1],
318            weighting_scheme="xyz", z_edge_mask=z_edges, beta=beta,
319        )
320    node_labels = multicut_decomposition(rag, costs)
321    seg = project_node_labels_to_pixels(rag, overseg, node_labels)
322
323    return seg.astype("uint64")

Instance segmentation for 3D EM data via slice-wise oversegmentation + multicut.

For each z-slice a convergence-density seeded watershed produces an oversegmentation. A region-adjacency graph is then lifted across all slices and a multicut optimisation yields the final 3D instances.

Arguments:
  • boundary_map: Boundary probability map, shape (Z, Y, X). Typically 1 - foreground or fg.max() - fg.
  • distances: In-plane distance channels (ydist, xdist), shape (2, Z, Y, X).
  • model_type: The SAM2 backbone the predictions came from, e.g. 'hvit_t'. Selects the default for any of the tunable parameters below left as None, see default_postprocessing.
  • beta: Multicut boundary bias; higher values favour more merging.
  • density_threshold: Convergence-density threshold for seed extraction in the slice-wise oversegmentation.
  • n_iter: Flow integration steps for the oversegmentation seeding.
  • dt: Flow integration step size.
  • sigma: Gaussian sigma for smoothing the convergence-density map.
  • n_threads: Number of threads for the parallel slice-wise oversegmentation.
Returns:

Instance segmentation, uint64 array, shape (Z, Y, X).