micro_sam.v2.transforms.labels
1from typing import Optional, Tuple 2from concurrent.futures import ThreadPoolExecutor 3 4import numpy as np 5 6from scipy.ndimage import binary_dilation 7 8from skimage.measure import regionprops 9from skimage.segmentation import find_boundaries 10 11from bioimage_cpp.segmentation import label as connected_components, relabel_sequential 12from bioimage_cpp.distance import distance_transform, geodesic_distance_field, vector_difference_transform 13 14 15# The integer dtypes that bioimage-cpp's connected-component labeling accepts. 16# Written into the foreground target channel, which otherwise holds 0 or 1, for voxels without ground truth. 17FOREGROUND_IGNORE_VALUE = -1 18 19SUPPORTED_LABEL_DTYPES = frozenset( 20 np.dtype(name) for name in ("bool", "uint8", "uint16", "uint32", "uint64", "int32", "int64") 21) 22 23 24def _instance_labels(labels): 25 """Relabel each connected region as a unique integer instance. 26 27 Wraps a connected-components labeling so that disconnected regions with the 28 same label ID get separate consecutive IDs. Used as label_transform2 in the 29 interactive generalist dataloaders. 30 """ 31 # bioimage-cpp reads raw bytes as native byte order; some EmbedSeg masks are big-endian. 32 if not labels.dtype.isnative: 33 labels = labels.byteswap().view(labels.dtype.newbyteorder()) 34 # bioimage-cpp accepts only bool, uint8/16/32/64 and int32/64. Cast anything else: some datasets store 35 # integer ids as floats (MoNuSeg, MoNuSAC) and others as narrow integers (Omnipose masks are int8 or int16). 36 if labels.dtype not in SUPPORTED_LABEL_DTYPES: 37 labels = labels.astype("int64") 38 return connected_components(labels).astype("int64") 39 40 41def semantic_labels(labels): 42 """Convert an instance segmentation into a three class semantic map. 43 44 Args: 45 labels: The instance segmentation. 46 47 Returns: 48 The semantic map, with 0 for the background, 1 for the object boundary and 2 for the object interior. 49 """ 50 instances = _instance_labels(labels) 51 semantic = np.zeros(instances.shape, dtype="int64") 52 semantic[instances > 0] = 2 53 # The inner boundary mode only marks pixels inside an object, so the boundary stays part of the foreground. 54 semantic[find_boundaries(instances, mode="inner")] = 1 55 return semantic 56 57 58def _axondeepseg_pre_label_transform(y): 59 """Extract axon instances from AxonDeepSeg semantic labels via connected components. 60 61 Runs before the sampler so MinInstanceSampler can count actual axon instances 62 rather than just binary foreground (0/1). 63 """ 64 return connected_components(y == 2).astype("uint32") 65 66 67def _astih_pre_label_transform(y, min_size=20): 68 """Extract axon instances from ASTIH semantic labels (0=background, 1=myelin, 2=axon). 69 70 Same encoding as AxonDeepSeg, so the axon class alone is taken: every myelinated fibre's 71 interior is fully ringed by its own sheath, which keeps neighbouring interiors disconnected. 72 Running connected components over the whole foreground instead would bridge touching sheaths. 73 Objects below *min_size* pixels are annotation specks and are dropped. 74 """ 75 instances = connected_components(y == 2).astype("uint32") 76 ids, counts = np.unique(instances, return_counts=True) 77 drop = ids[(counts < min_size) & (ids > 0)] 78 if drop.size: 79 instances[np.isin(instances, drop)] = 0 80 instances = connected_components(instances > 0).astype("uint32") 81 return instances 82 83 84def _compact_label_ids(labels, keep=()): 85 """Relabel the instances to 1..n, keeping the ids in ``keep`` as they are. 86 87 The flip augmentation casts labels to float32 and back, which merges ids above 2^24: connectomics volumes 88 number their neurons far beyond that. Runs as the label_transform, after the sampler and before the flips. 89 """ 90 labels = np.asarray(labels) 91 ids = np.unique(labels) 92 lut = np.zeros(len(ids), dtype="int64") 93 instances = (ids != 0) & ~np.isin(ids, keep) 94 lut[instances] = np.arange(1, int(instances.sum()) + 1) 95 for value in keep: 96 lut[ids == value] = value 97 return lut[np.searchsorted(ids, labels)] 98 99 100def _labels_to_uint32(labels): 101 """Widen labels so that an ignore label fits. torch_em recasts labels to their loaded dtype before 102 label_transform2, so this has to run as the pre_label_transform.""" 103 return np.asarray(labels).astype("uint32") 104 105 106def _connected_components_pre_label_trafo(labels, ignore_label=None, foreground_class=None): 107 """Connected components of a patch, as the pre_label_transform, so that the sampler counts instances. 108 109 torch_em runs the sampler before label_transform2, so without this a sampler sees binary or semantic labels as 110 one id. Touching objects with different ids stay separate, and the disconnected pieces of one id become separate 111 instances. The output is uint32, which torch_em keeps as the loaded dtype. 112 113 Args: 114 labels: The label patch. 115 ignore_label: The id of the ignored voxels, which keep their id and are not labeled. 116 foreground_class: For semantic labels, the class whose mask is labeled; all other classes are background. 117 """ 118 labels = np.asarray(labels) 119 ignore = None if ignore_label is None else labels == ignore_label 120 if foreground_class is not None: 121 labels = labels == foreground_class 122 if ignore is not None: 123 labels = np.where(ignore, 0, labels) 124 if labels.dtype != bool: 125 labels = labels.astype("uint32") 126 instances = connected_components(labels).astype("uint32") 127 if ignore is not None: 128 instances[ignore] = ignore_label 129 return instances 130 131 132def _ignore_missing_raw_trafo( 133 raw, labels, ignore_label, normalizer=None, min_area=4096, transform=None, any_constant=False 134): 135 """Mark labels as *ignore_label* where the raw holds a missing tile, normalize the raw, then apply *transform*. 136 137 A missing tile is a connected region of exact zeros in a slice with at least *min_area* pixels. With 138 *any_constant*, it is a connected region of any one constant value. Some volumes fill missing data with such a 139 value, for example 128 or a saturated 254. The test needs the stored intensities, since a percentile 140 normalization clips dark tissue to zero as well, so the leaf's raw_transform must leave the normalization to 141 *normalizer*, which runs here after the test. Runs as the joint 'transform', so it sees the raw and precedes 142 label_transform2. The loaded label dtype must hold *ignore_label*, see :func:`_labels_to_uint32`. 143 """ 144 raw = np.asarray(raw) 145 labels = np.asarray(labels) 146 if any_constant: 147 # The channels of the prepared raw are copies, so the first one holds the stored intensities. 148 values = raw[0] if raw.ndim == labels.ndim + 1 else raw 149 zero = np.zeros(values.shape, dtype=bool) 150 else: 151 zero = np.all(raw == 0, axis=0) if raw.ndim == labels.ndim + 1 else raw == 0 152 missing = np.zeros_like(zero) 153 slices = zero if zero.ndim == 3 else zero[None] 154 out = missing if missing.ndim == 3 else missing[None] 155 for z in range(slices.shape[0]): 156 if any_constant: 157 plane = values[z] if values.ndim == 3 else values 158 # Connected components of equal-valued pixels: every value gets an id above the background 0. 159 value_ids = np.unique(plane, return_inverse=True)[1].reshape(plane.shape).astype("uint32") + 1 160 components = connected_components(value_ids) 161 else: 162 components = connected_components(slices[z]) 163 if components.max() == 0: 164 continue 165 areas = np.bincount(components.ravel().astype("int64")) 166 big = np.flatnonzero(areas >= min_area) 167 big = big[big > 0] 168 if big.size: 169 out[z] = np.isin(components, big) 170 if missing.any(): 171 if labels.dtype.kind in "ui" and ignore_label > np.iinfo(labels.dtype).max: 172 labels = labels.astype("uint32") 173 else: 174 labels = labels.copy() 175 labels[missing] = ignore_label 176 if normalizer is not None: 177 raw = normalizer(raw) 178 if transform is not None: 179 raw, labels = transform(raw, labels) 180 return raw, labels 181 182 183def _ignore_unlabelled_blobs_trafo(raw, labels, ignore_label, min_area=20000, transform=None): 184 """Mark large connected unlabelled regions as *ignore_label*, then apply *transform*. 185 186 For volumes where somata or vessels were left out of the segmentation. Extracellular space 187 and membranes form thin unlabelled seams far below *min_area*, so they stay background. 188 """ 189 labels = np.asarray(labels) 190 background = labels == 0 191 blobs = np.zeros_like(background) 192 slices = background if background.ndim == 3 else background[None] 193 out = blobs if blobs.ndim == 3 else blobs[None] 194 for z in range(slices.shape[0]): 195 components = connected_components(slices[z]) 196 if components.max() == 0: 197 continue 198 areas = np.bincount(components.ravel().astype("int64")) 199 big = np.flatnonzero(areas >= min_area) 200 big = big[big > 0] 201 if big.size: 202 out[z] = np.isin(components, big) 203 if blobs.any(): 204 if labels.dtype.kind in "ui" and ignore_label > np.iinfo(labels.dtype).max: 205 labels = labels.astype("uint32") 206 else: 207 labels = labels.copy() 208 labels[blobs] = ignore_label 209 if transform is not None: 210 raw, labels = transform(raw, labels) 211 return raw, labels 212 213 214def _em_cell_label_trafo(y, label_trafo, ignore_label=None): 215 # Take the ignore mask before label_trafo, which replaces the instance ids with distances. 216 ignore = None if ignore_label is None else np.asarray(y) == ignore_label 217 y = label_trafo(y) 218 219 # Prepare the true background. 220 instances = y[0] 221 222 bd = find_boundaries(instances.astype("uint32"), mode="outer").astype("uint8") 223 fg = (instances > 0).astype("uint8") 224 expected_fg = (fg & ~bd).astype("float32") 225 if ignore is not None: 226 expected_fg[ignore] = FOREGROUND_IGNORE_VALUE 227 228 expected_y = np.concatenate([expected_fg[None], y[2:]], axis=0) 229 230 return expected_y 231 232 233def _plantseg_label_trafo(y, data, label_trafo): 234 """Map the PlantSeg unannotated regions to ignore and the background id to 0. 235 236 In root, label 1 is the background and label 0 the unannotated deeper tissue. In ovules (with the 237 'label_with_ignore' key), 0 is the background and -1 marks the unannotated regions. 238 """ 239 if data == "root": 240 ignore = y == 0 241 y[y == 1] = 0 242 elif data == "ovules": 243 ignore = y == -1 244 y[ignore] = 0 245 else: 246 raise ValueError 247 248 if label_trafo is None: 249 return y 250 251 y = label_trafo(y) 252 fg_channel = 1 if getattr(label_trafo, "instances", False) else 0 253 y[fg_channel][ignore] = FOREGROUND_IGNORE_VALUE 254 return y 255 256 257def _ignore_label_trafo(y, ignore_label, label_trafo=None): 258 """Exclude the voxels that carry *ignore_label* from the foreground target, then apply *label_trafo*. 259 260 The ignored voxels count as background for *label_trafo* and are set to FOREGROUND_IGNORE_VALUE in its 261 foreground channel, so that no loss term supervises them. Without a *label_trafo* they are only set to 0. 262 """ 263 ignore = np.asarray(y) == ignore_label 264 y = np.where(ignore, 0, y) 265 if label_trafo is None: 266 return y 267 268 y = label_trafo(y) 269 # An instance map without a channel axis has no foreground channel, and its ignored voxels are 0 already. 270 if np.ndim(y) == ignore.ndim: 271 return y 272 if getattr(label_trafo, "instances", False): 273 # The instance channel feeds the interactive branch, which samples objects from it. 274 y[0][ignore] = 0 275 y[1][ignore] = FOREGROUND_IGNORE_VALUE 276 else: 277 y[0][ignore] = FOREGROUND_IGNORE_VALUE 278 return y 279 280 281def _drop_oversized_label_trafo(y, max_fraction, label_trafo): 282 """Drop instances that cover more than `max_fraction` of the patch, then apply the usual transform. 283 284 Some datasets carry a single annotation artefact that covers a large region of tissue as though it were 285 one object. NIS3D has one such blob in three of its six volumes, 56x larger than its largest real nucleus, 286 so any instance above a few percent of a patch is certainly not a nucleus. 287 """ 288 ids, counts = np.unique(y[y > 0], return_counts=True) 289 oversized = ids[counts > max_fraction * y.size] 290 if len(oversized) > 0: 291 y = y.copy() 292 y[np.isin(y, oversized)] = 0 293 294 if label_trafo is None: 295 return y 296 297 return label_trafo(y) 298 299 300def _decode_colour_cycled_labels(y, label_trafo=None): 301 """Recover instances from labels that reuse a small palette of ids across many objects. 302 303 NISNet3D stores its instance segmentation as a graph colouring: only 4-5 id values are cycled over 304 dozens of nuclei so that no two touching nuclei share one. Running connected components over the whole 305 array therefore fuses same-coloured neighbours, while running it within each id separately recovers the 306 true objects. 307 """ 308 decoded = np.zeros(y.shape, dtype="int64") 309 offset = 0 310 for value in np.unique(y): 311 if value == 0: 312 continue 313 components = connected_components((y == value).astype("uint8")) 314 mask = components > 0 315 decoded[mask] = components[mask].astype("int64") + offset 316 offset = int(decoded.max()) 317 318 if label_trafo is None: 319 return decoded 320 321 return label_trafo(decoded) 322 323 324def _merge_instance_channels(y, label_trafo=None): 325 """Merge a stack of disjoint instance maps into one, offsetting the ids of each channel. 326 327 mnDINO stores nuclei and micronuclei as two separate instance maps of the same image. They never 328 overlap, so they can be combined into a single target by shifting the second map's ids past the first. 329 """ 330 merged = np.zeros(y.shape[1:], dtype="int64") 331 offset = 0 332 for channel in y: 333 mask = channel > 0 334 if not mask.any(): 335 continue 336 merged[mask] = channel[mask].astype("int64") + offset 337 offset = int(merged.max()) 338 339 if label_trafo is None: 340 return merged 341 342 return label_trafo(merged) 343 344 345def _background_id_label_trafo(y, background_id, label_trafo): 346 """Map a non-zero background id to 0 before applying the usual label transform. 347 348 Some datasets number the background as an ordinary instance rather than 0, so it would otherwise be 349 trained as one very large object. PlantSeg root uses id 1 and PNAS Arabidopsis does the same. 350 """ 351 y[y == background_id] = 0 352 353 if label_trafo is None: 354 return y 355 356 return label_trafo(y) 357 358 359def _joint_em_cell_label_trafo(y, label_trafo, ignore_label=None): 360 """EM label transform for joint training - keeps instance IDs as channel 0. 361 362 Like :func:`_em_cell_label_trafo` but returns 363 ``[instance_ids, expected_fg, d_x, d_y, d_z]`` (5 channels) instead of 364 dropping the instance channel. ``label_trafo`` must produce a 5-channel 365 array (i.e. be a :class:`_JointLabelTransform` / ``instances=True``). 366 """ 367 ignore = None if ignore_label is None else np.asarray(y) == ignore_label 368 y = label_trafo(y) # (5, H, W) or (5, Z, H, W) 369 instances = y[0] 370 bd = find_boundaries(instances.astype("uint32"), mode="outer").astype("uint8") 371 fg = (instances > 0).astype("uint8") 372 expected_fg = (fg & ~bd).astype("float32") 373 if ignore is not None: 374 expected_fg[ignore] = FOREGROUND_IGNORE_VALUE 375 # Channel 0 feeds the interactive branch, which samples objects from it (largest first). 376 instances = np.where(ignore, 0, instances) 377 return np.concatenate([instances[None], expected_fg[None], y[2:]], axis=0) 378 379 380def object_boundaries(labels: np.ndarray) -> np.ndarray: 381 """Return a dilated mask of all object boundaries. 382 383 The transform dilates each inner boundary once. The target includes isolated objects and objects that touch. 384 """ 385 boundary = find_boundaries(np.asarray(labels), mode="inner") 386 if boundary.any(): 387 boundary = binary_dilation(boundary, iterations=1) 388 return boundary 389 390 391class DirectedPerObjectBoundaryDistanceTransform: 392 """Compute directed-distance targets with an optional boundary channel. 393 394 The channel layout is ``[instance_ids?, foreground?, d_z, d_y, d_x, boundaries?]``. 395 396 Args: 397 min_size: The minimum object size. The transform removes smaller objects. 398 foreground: The flag to prepend the binary foreground mask. 399 instances: The flag to prepend the instance IDs. 400 apply_label: The flag to relabel the input with connected components. 401 sampling: The voxel spacing for anisotropic data. 402 with_boundaries: The flag to append the full object-boundary mask. 403 n_threads: The number of threads for distance computation across objects. 404 """ 405 eps = 1e-7 406 407 def __init__( 408 self, 409 min_size: int = 0, 410 foreground: bool = True, 411 instances: bool = False, 412 apply_label: bool = True, 413 sampling: Optional[Tuple[float, ...]] = None, 414 with_boundaries: bool = False, 415 n_threads: int = 1, 416 ): 417 self.min_size = min_size 418 self.n_threads = n_threads 419 self.distance_fill_value = 1 420 self.foreground = foreground 421 self.instances = instances 422 self.apply_label = apply_label 423 self.sampling = sampling 424 self.with_boundaries = with_boundaries 425 426 def compute_normalized_directed_distances(self, labels, label_id, boundaries, bb, distances): 427 """@private 428 """ 429 cropped_mask = labels[bb] == label_id 430 inv_mask = ~cropped_mask 431 432 cropped_boundary_mask = boundaries[bb] 433 434 # Inverted mask ('== 0') gives the vector to the nearest boundary, matching vigra's 435 # 'vectorDistanceTransform' (as migrated in torch_em); 'sampling' replaces 'pixel_pitch'. 436 kwargs = {} if self.sampling is None else {"sampling": self.sampling} 437 this_distances = vector_difference_transform(cropped_boundary_mask == 0, **kwargs) 438 this_distances[inv_mask] = 0 439 440 spatial_axes = tuple(range(labels.ndim)) 441 this_distances /= (np.abs(this_distances).max(axis=spatial_axes, keepdims=True) + self.eps) 442 443 distances[bb][cropped_mask] = this_distances[cropped_mask] 444 return distances 445 446 def __call__(self, labels: np.ndarray) -> np.ndarray: 447 """Compute the per object distance transform. 448 449 Args: 450 labels: The segmentation 451 452 Returns: 453 The distances. 454 """ 455 is_2d = (labels.ndim == 2) 456 457 if labels.ndim == 2: 458 labels = labels[None] 459 460 # bioimage-cpp and skimage C extensions read raw bytes as native byte order. Swap if needed. 461 if not labels.dtype.isnative: 462 labels = labels.byteswap().view(labels.dtype.newbyteorder()) 463 464 if self.apply_label: 465 # Cast to uint32: connected_components rejects int16 and labels fit uint32. 466 labels = connected_components(labels.astype("uint32")).astype("uint32") 467 else: # Otherwise just relabel the segmentation. 468 # Cast to uint32: relabel_sequential rejects uint8/16 and labels fit uint32. 469 labels = relabel_sequential(labels.astype("uint32"))[0].astype("uint32") 470 471 # Filter out small objects if min_size is specified. 472 if self.min_size > 0: 473 ids, sizes = np.unique(labels, return_counts=True) 474 discard_ids = ids[sizes < self.min_size] 475 labels[np.isin(labels, discard_ids)] = 0 476 labels = relabel_sequential(labels)[0].astype("uint32") 477 478 # Compute the boundaries. 479 boundaries = find_boundaries(labels, mode="inner").astype("uint32") 480 481 # Compute region properties to derive bounding boxes and centers. 482 ndim = labels.ndim 483 props = regionprops(labels) 484 bounding_boxes = { 485 prop.label: tuple(slice(prop.bbox[i], prop.bbox[i + ndim]) for i in range(ndim)) for prop in props 486 } 487 488 # Compute how many distance channels we have. 489 n_channels = 3 490 491 # Compute the per object distances. Each object writes only into its own voxels and the distance 492 # solvers release the GIL, so the objects can be processed by a thread pool. 493 distances = np.full(labels.shape + (n_channels,), self.distance_fill_value, dtype="float32") 494 495 def compute(prop): 496 self.compute_normalized_directed_distances( 497 labels, prop.label, boundaries, bounding_boxes[prop.label], distances 498 ) 499 500 if self.n_threads > 1: 501 with ThreadPoolExecutor(self.n_threads) as pool: 502 list(pool.map(compute, props)) 503 else: 504 for prop in props: 505 compute(prop) 506 507 # Bring the distance channel to the first dimension. 508 to_channel_first = (ndim,) + tuple(range(ndim)) 509 distances = distances.transpose(to_channel_first) 510 511 if self.with_boundaries: 512 boundaries = object_boundaries(labels).astype("float32") 513 distances = np.concatenate([distances, boundaries[None]], axis=0) 514 515 # Add the foreground mask as first channel if specified. 516 if self.foreground: 517 binary_labels = (labels > 0).astype("float32") 518 distances = np.concatenate([binary_labels[None], distances], axis=0) 519 520 if self.instances: 521 distances = np.concatenate([labels[None].astype("float32"), distances], axis=0) 522 523 if is_2d: 524 assert distances.ndim == 4 525 assert distances.shape[1] == 1 526 distances = distances.squeeze(1) 527 528 return distances 529 530 531def _geodesic_object_center(mask, sampling): 532 """Point of maximal distance to the boundary, which always lies inside the object. 533 534 The mask is padded so that the crop face counts as a boundary, which keeps the center off a 535 face where an object was cut. The padding does not enter any output field. 536 537 Singleton axes are left unpadded. A 2d input is promoted to a single z slice, and padding that 538 axis would put background one voxel away from every single voxel, flattening the distance field 539 and making the argmax arbitrary. 540 """ 541 kwargs = {} if sampling is None else {"sampling": sampling} 542 pad_width = tuple((1, 1) if extent > 1 else (0, 0) for extent in mask.shape) 543 inner = tuple(slice(1, -1) if extent > 1 else slice(None) for extent in mask.shape) 544 boundary_distance = distance_transform(np.pad(mask, pad_width), **kwargs)[inner] 545 return np.unravel_index(int(np.argmax(np.where(mask, boundary_distance, -1.0))), mask.shape) 546 547 548def _finite_fill(field, mask): 549 """Replace the +inf that a geodesic solve returns for voxels it cannot reach. 550 551 Only disconnected objects have unreachable voxels, which ``apply_label`` already prevents. 552 """ 553 reachable = mask & np.isfinite(field) 554 fill = field[reachable].max() if reachable.any() else 0.0 555 return np.where(reachable, field, fill).astype("float32") 556 557 558class GeodesicHybridDistanceTransform(DirectedPerObjectBoundaryDistanceTransform): 559 """Directed distances whose direction comes from the geodesic field around the object center. 560 561 Same output layout as :class:`DirectedPerObjectBoundaryDistanceTransform`, so it is a drop-in 562 replacement as ``label_transform2``. Only the vector at each pixel differs: it is the gradient 563 of the geodesic distance field from the object's center, scaled by the geodesic distance to the 564 boundary. 565 566 The two parts do different jobs downstream and neither works alone. The direction makes the 567 flow in :func:`micro_sam.v2.postprocessing.flow_instance_segmentation` converge to a single sink 568 per object whatever its shape, where a boundary referenced direction converges onto a medial 569 axis and so over-segments elongated objects. The magnitude is what 570 :func:`micro_sam.v2.postprocessing.watershed_heightmap` inverts into the ridge between touching 571 objects, which a unit norm field cannot provide. 572 """ 573 574 def compute_normalized_directed_distances(self, labels, label_id, boundaries, bb, distances): 575 """@private 576 """ 577 cropped_mask = labels[bb] == label_id 578 ndim = labels.ndim 579 kwargs = {} if self.sampling is None else {"sampling": self.sampling} 580 581 # The object's own boundary, not the shared one the euclidean transform uses: a geodesic 582 # solve needs its sources inside the mask it propagates through. 583 sources = np.argwhere(find_boundaries(cropped_mask, mode="inner") & cropped_mask) 584 if len(sources) == 0: # A one voxel wide object is all boundary. 585 return distances 586 587 boundary_field = _finite_fill(geodesic_distance_field(cropped_mask, sources, **kwargs), cropped_mask) 588 center = _geodesic_object_center(cropped_mask, self.sampling) 589 gradient = geodesic_distance_field( 590 cropped_mask, np.array(center), return_gradient=True, **kwargs 591 )[1] 592 gradient[~np.isfinite(gradient)] = 0.0 593 594 this_distances = gradient * boundary_field[..., None] 595 spatial_axes = tuple(range(ndim)) 596 this_distances /= (np.abs(this_distances).max(axis=spatial_axes, keepdims=True) + self.eps) 597 598 distances[bb][cropped_mask] = this_distances[cropped_mask] 599 return distances 600 601 602class _JointLabelTransform(DirectedPerObjectBoundaryDistanceTransform): 603 """Distance transform for joint interactive + automatic training. 604 605 This transform sets ``instances=True`` by default. 606 The output layout is ``[instance_ids, foreground_mask, d_z, d_y, d_x, boundaries?]``. 607 Set ``with_boundaries=True`` to append the sixth channel. 608 609 The interactive branch uses channel 0 (cast to int64 as instance IDs) 610 and the automatic branch uses channels 1 onward. 611 """ 612 613 def __init__(self, instances: bool = True, **kwargs): 614 super().__init__(instances=instances, **kwargs) 615 616 617class _JointGeodesicLabelTransform(GeodesicHybridDistanceTransform): 618 """Geodesic hybrid distance transform for joint interactive + automatic training. 619 620 The output layout is ``[instance_ids, foreground_mask, d_z, d_y, d_x, boundaries?]``. 621 The directed distances come from the geodesic field around each object's center. 622 """ 623 624 def __init__(self, instances: bool = True, **kwargs): 625 super().__init__(instances=instances, **kwargs)
42def semantic_labels(labels): 43 """Convert an instance segmentation into a three class semantic map. 44 45 Args: 46 labels: The instance segmentation. 47 48 Returns: 49 The semantic map, with 0 for the background, 1 for the object boundary and 2 for the object interior. 50 """ 51 instances = _instance_labels(labels) 52 semantic = np.zeros(instances.shape, dtype="int64") 53 semantic[instances > 0] = 2 54 # The inner boundary mode only marks pixels inside an object, so the boundary stays part of the foreground. 55 semantic[find_boundaries(instances, mode="inner")] = 1 56 return semantic
Convert an instance segmentation into a three class semantic map.
Arguments:
- labels: The instance segmentation.
Returns:
The semantic map, with 0 for the background, 1 for the object boundary and 2 for the object interior.
381def object_boundaries(labels: np.ndarray) -> np.ndarray: 382 """Return a dilated mask of all object boundaries. 383 384 The transform dilates each inner boundary once. The target includes isolated objects and objects that touch. 385 """ 386 boundary = find_boundaries(np.asarray(labels), mode="inner") 387 if boundary.any(): 388 boundary = binary_dilation(boundary, iterations=1) 389 return boundary
Return a dilated mask of all object boundaries.
The transform dilates each inner boundary once. The target includes isolated objects and objects that touch.
392class DirectedPerObjectBoundaryDistanceTransform: 393 """Compute directed-distance targets with an optional boundary channel. 394 395 The channel layout is ``[instance_ids?, foreground?, d_z, d_y, d_x, boundaries?]``. 396 397 Args: 398 min_size: The minimum object size. The transform removes smaller objects. 399 foreground: The flag to prepend the binary foreground mask. 400 instances: The flag to prepend the instance IDs. 401 apply_label: The flag to relabel the input with connected components. 402 sampling: The voxel spacing for anisotropic data. 403 with_boundaries: The flag to append the full object-boundary mask. 404 n_threads: The number of threads for distance computation across objects. 405 """ 406 eps = 1e-7 407 408 def __init__( 409 self, 410 min_size: int = 0, 411 foreground: bool = True, 412 instances: bool = False, 413 apply_label: bool = True, 414 sampling: Optional[Tuple[float, ...]] = None, 415 with_boundaries: bool = False, 416 n_threads: int = 1, 417 ): 418 self.min_size = min_size 419 self.n_threads = n_threads 420 self.distance_fill_value = 1 421 self.foreground = foreground 422 self.instances = instances 423 self.apply_label = apply_label 424 self.sampling = sampling 425 self.with_boundaries = with_boundaries 426 427 def compute_normalized_directed_distances(self, labels, label_id, boundaries, bb, distances): 428 """@private 429 """ 430 cropped_mask = labels[bb] == label_id 431 inv_mask = ~cropped_mask 432 433 cropped_boundary_mask = boundaries[bb] 434 435 # Inverted mask ('== 0') gives the vector to the nearest boundary, matching vigra's 436 # 'vectorDistanceTransform' (as migrated in torch_em); 'sampling' replaces 'pixel_pitch'. 437 kwargs = {} if self.sampling is None else {"sampling": self.sampling} 438 this_distances = vector_difference_transform(cropped_boundary_mask == 0, **kwargs) 439 this_distances[inv_mask] = 0 440 441 spatial_axes = tuple(range(labels.ndim)) 442 this_distances /= (np.abs(this_distances).max(axis=spatial_axes, keepdims=True) + self.eps) 443 444 distances[bb][cropped_mask] = this_distances[cropped_mask] 445 return distances 446 447 def __call__(self, labels: np.ndarray) -> np.ndarray: 448 """Compute the per object distance transform. 449 450 Args: 451 labels: The segmentation 452 453 Returns: 454 The distances. 455 """ 456 is_2d = (labels.ndim == 2) 457 458 if labels.ndim == 2: 459 labels = labels[None] 460 461 # bioimage-cpp and skimage C extensions read raw bytes as native byte order. Swap if needed. 462 if not labels.dtype.isnative: 463 labels = labels.byteswap().view(labels.dtype.newbyteorder()) 464 465 if self.apply_label: 466 # Cast to uint32: connected_components rejects int16 and labels fit uint32. 467 labels = connected_components(labels.astype("uint32")).astype("uint32") 468 else: # Otherwise just relabel the segmentation. 469 # Cast to uint32: relabel_sequential rejects uint8/16 and labels fit uint32. 470 labels = relabel_sequential(labels.astype("uint32"))[0].astype("uint32") 471 472 # Filter out small objects if min_size is specified. 473 if self.min_size > 0: 474 ids, sizes = np.unique(labels, return_counts=True) 475 discard_ids = ids[sizes < self.min_size] 476 labels[np.isin(labels, discard_ids)] = 0 477 labels = relabel_sequential(labels)[0].astype("uint32") 478 479 # Compute the boundaries. 480 boundaries = find_boundaries(labels, mode="inner").astype("uint32") 481 482 # Compute region properties to derive bounding boxes and centers. 483 ndim = labels.ndim 484 props = regionprops(labels) 485 bounding_boxes = { 486 prop.label: tuple(slice(prop.bbox[i], prop.bbox[i + ndim]) for i in range(ndim)) for prop in props 487 } 488 489 # Compute how many distance channels we have. 490 n_channels = 3 491 492 # Compute the per object distances. Each object writes only into its own voxels and the distance 493 # solvers release the GIL, so the objects can be processed by a thread pool. 494 distances = np.full(labels.shape + (n_channels,), self.distance_fill_value, dtype="float32") 495 496 def compute(prop): 497 self.compute_normalized_directed_distances( 498 labels, prop.label, boundaries, bounding_boxes[prop.label], distances 499 ) 500 501 if self.n_threads > 1: 502 with ThreadPoolExecutor(self.n_threads) as pool: 503 list(pool.map(compute, props)) 504 else: 505 for prop in props: 506 compute(prop) 507 508 # Bring the distance channel to the first dimension. 509 to_channel_first = (ndim,) + tuple(range(ndim)) 510 distances = distances.transpose(to_channel_first) 511 512 if self.with_boundaries: 513 boundaries = object_boundaries(labels).astype("float32") 514 distances = np.concatenate([distances, boundaries[None]], axis=0) 515 516 # Add the foreground mask as first channel if specified. 517 if self.foreground: 518 binary_labels = (labels > 0).astype("float32") 519 distances = np.concatenate([binary_labels[None], distances], axis=0) 520 521 if self.instances: 522 distances = np.concatenate([labels[None].astype("float32"), distances], axis=0) 523 524 if is_2d: 525 assert distances.ndim == 4 526 assert distances.shape[1] == 1 527 distances = distances.squeeze(1) 528 529 return distances
Compute directed-distance targets with an optional boundary channel.
The channel layout is [instance_ids?, foreground?, d_z, d_y, d_x, boundaries?].
Arguments:
- min_size: The minimum object size. The transform removes smaller objects.
- foreground: The flag to prepend the binary foreground mask.
- instances: The flag to prepend the instance IDs.
- apply_label: The flag to relabel the input with connected components.
- sampling: The voxel spacing for anisotropic data.
- with_boundaries: The flag to append the full object-boundary mask.
- n_threads: The number of threads for distance computation across objects.
408 def __init__( 409 self, 410 min_size: int = 0, 411 foreground: bool = True, 412 instances: bool = False, 413 apply_label: bool = True, 414 sampling: Optional[Tuple[float, ...]] = None, 415 with_boundaries: bool = False, 416 n_threads: int = 1, 417 ): 418 self.min_size = min_size 419 self.n_threads = n_threads 420 self.distance_fill_value = 1 421 self.foreground = foreground 422 self.instances = instances 423 self.apply_label = apply_label 424 self.sampling = sampling 425 self.with_boundaries = with_boundaries
559class GeodesicHybridDistanceTransform(DirectedPerObjectBoundaryDistanceTransform): 560 """Directed distances whose direction comes from the geodesic field around the object center. 561 562 Same output layout as :class:`DirectedPerObjectBoundaryDistanceTransform`, so it is a drop-in 563 replacement as ``label_transform2``. Only the vector at each pixel differs: it is the gradient 564 of the geodesic distance field from the object's center, scaled by the geodesic distance to the 565 boundary. 566 567 The two parts do different jobs downstream and neither works alone. The direction makes the 568 flow in :func:`micro_sam.v2.postprocessing.flow_instance_segmentation` converge to a single sink 569 per object whatever its shape, where a boundary referenced direction converges onto a medial 570 axis and so over-segments elongated objects. The magnitude is what 571 :func:`micro_sam.v2.postprocessing.watershed_heightmap` inverts into the ridge between touching 572 objects, which a unit norm field cannot provide. 573 """ 574 575 def compute_normalized_directed_distances(self, labels, label_id, boundaries, bb, distances): 576 """@private 577 """ 578 cropped_mask = labels[bb] == label_id 579 ndim = labels.ndim 580 kwargs = {} if self.sampling is None else {"sampling": self.sampling} 581 582 # The object's own boundary, not the shared one the euclidean transform uses: a geodesic 583 # solve needs its sources inside the mask it propagates through. 584 sources = np.argwhere(find_boundaries(cropped_mask, mode="inner") & cropped_mask) 585 if len(sources) == 0: # A one voxel wide object is all boundary. 586 return distances 587 588 boundary_field = _finite_fill(geodesic_distance_field(cropped_mask, sources, **kwargs), cropped_mask) 589 center = _geodesic_object_center(cropped_mask, self.sampling) 590 gradient = geodesic_distance_field( 591 cropped_mask, np.array(center), return_gradient=True, **kwargs 592 )[1] 593 gradient[~np.isfinite(gradient)] = 0.0 594 595 this_distances = gradient * boundary_field[..., None] 596 spatial_axes = tuple(range(ndim)) 597 this_distances /= (np.abs(this_distances).max(axis=spatial_axes, keepdims=True) + self.eps) 598 599 distances[bb][cropped_mask] = this_distances[cropped_mask] 600 return distances
Directed distances whose direction comes from the geodesic field around the object center.
Same output layout as DirectedPerObjectBoundaryDistanceTransform, so it is a drop-in
replacement as label_transform2. Only the vector at each pixel differs: it is the gradient
of the geodesic distance field from the object's center, scaled by the geodesic distance to the
boundary.
The two parts do different jobs downstream and neither works alone. The direction makes the
flow in micro_sam.v2.postprocessing.flow_instance_segmentation() converge to a single sink
per object whatever its shape, where a boundary referenced direction converges onto a medial
axis and so over-segments elongated objects. The magnitude is what
micro_sam.v2.postprocessing.watershed_heightmap() inverts into the ridge between touching
objects, which a unit norm field cannot provide.