micro_sam.v1.multi_dimensional_segmentation
Multi-dimensional segmentation with segment anything.
1"""Multi-dimensional segmentation with segment anything. 2""" 3 4import os 5import warnings 6from pathlib import Path 7import multiprocessing as mp 8from concurrent import futures 9import xml.etree.ElementTree as ET 10from collections import defaultdict 11from importlib.util import find_spec 12from typing import Dict, List, Optional, Union, Tuple 13 14try: 15 from trackastra.model import Trackastra 16 from trackastra.tracking import graph_to_ctc, graph_to_napari_tracks 17 TRACKASTRA_IMPORT_ERROR = None 18except ImportError as e: 19 Trackastra = None 20 graph_to_ctc = None 21 graph_to_napari_tracks = None 22 TRACKASTRA_IMPORT_ERROR = e 23 24import numpy as np 25import networkx as nx 26import imageio.v3 as imageio 27from skimage.measure import regionprops 28from scipy.ndimage import binary_closing 29from segment_anything.predictor import SamPredictor 30 31import torch 32 33import elf.segmentation as seg_utils 34import elf.tracking.tracking_utils as track_utils 35from elf.tracking.motile_tracking import recolor_segmentation 36 37from bioimage_cpp.graph import UndirectedGraph 38from bioimage_cpp.utils import segmentation_overlap 39from bioimage_cpp.segmentation import label, relabel_sequential 40 41from .. import util 42from ..util import AutoSegBase 43from .util import precompute_image_embeddings 44from .prompt_based_segmentation import segment_from_mask 45 46 47PROJECTION_MODES = ("box", "mask", "points", "points_and_mask", "single_point") 48 49 50def _validate_projection(projection): 51 use_single_point = False 52 if isinstance(projection, str): 53 if projection == "mask": 54 use_box, use_mask, use_points = True, True, False 55 elif projection == "points": 56 use_box, use_mask, use_points = False, False, True 57 elif projection == "box": 58 use_box, use_mask, use_points = True, False, False 59 elif projection == "points_and_mask": 60 use_box, use_mask, use_points = False, True, True 61 elif projection == "single_point": 62 use_box, use_mask, use_points = False, False, True 63 use_single_point = True 64 else: 65 raise ValueError( 66 "Choose projection method from 'mask' / 'points' / 'box' / 'points_and_mask' / 'single_point'. " 67 f"You have passed the invalid option {projection}." 68 ) 69 elif isinstance(projection, dict): 70 assert len(projection.keys()) == 3, "There should be three parameters assigned for the projection method." 71 use_box, use_mask, use_points = projection["use_box"], projection["use_mask"], projection["use_points"] 72 else: 73 raise ValueError(f"{projection} is not a supported projection method.") 74 return use_box, use_mask, use_points, use_single_point 75 76 77# Advanced stopping criterions. 78# In practice these did not make a big difference, so we do not use this at the moment. 79# We still leave it here for reference. 80def _advanced_stopping_criteria( 81 z, seg_z, seg_prev, z_start, z_increment, segmentation, criterion_choice, score, increment 82): 83 def _compute_mean_iou_for_n_slices(z, increment, seg_z, n_slices): 84 iou_list = [ 85 util.compute_iou(segmentation[z - increment * _slice], seg_z) for _slice in range(1, n_slices+1) 86 ] 87 return np.mean(iou_list) 88 89 if criterion_choice == 1: 90 # 1. current metric: iou of current segmentation and the previous slice 91 iou = util.compute_iou(seg_prev, seg_z) 92 criterion = iou 93 94 elif criterion_choice == 2: 95 # 2. combining SAM iou + iou: curr. slice & first segmented slice + iou: curr. slice vs prev. slice 96 iou = util.compute_iou(seg_prev, seg_z) 97 ff_iou = util.compute_iou(segmentation[z_start], seg_z) 98 criterion = 0.5 * iou + 0.3 * score + 0.2 * ff_iou 99 100 elif criterion_choice == 3: 101 # 3. iou of current segmented slice w.r.t the previous n slices 102 criterion = _compute_mean_iou_for_n_slices(z, increment, seg_z, min(5, abs(z - z_start))) 103 104 return criterion 105 106 107def segment_mask_in_volume( 108 segmentation: np.ndarray, 109 predictor: SamPredictor, 110 image_embeddings: util.ImageEmbeddings, 111 segmented_slices: np.ndarray, 112 stop_lower: bool, 113 stop_upper: bool, 114 iou_threshold: float, 115 projection: Union[str, dict], 116 update_progress: Optional[callable] = None, 117 box_extension: float = 0.0, 118 verbose: bool = False, 119) -> Tuple[np.ndarray, Tuple[int, int]]: 120 """Segment an object mask in in volumetric data. 121 122 Args: 123 segmentation: The initial segmentation for the object. 124 predictor: The Segment Anything predictor. 125 image_embeddings: The precomputed image embeddings for the volume. 126 segmented_slices: List of slices for which this object has already been segmented. 127 stop_lower: Whether to stop at the lowest segmented slice. 128 stop_upper: Wheter to stop at the topmost segmented slice. 129 iou_threshold: The IOU threshold for continuing segmentation across 3d. 130 projection: The projection method to use. One of 'box', 'mask', 'points', 'points_and_mask' or 'single point'. 131 Pass a dictionary to choose the excact combination of projection modes. 132 update_progress: Callback to update an external progress bar. 133 box_extension: Extension factor for increasing the box size after projection. 134 By default, does not increase the projected box size. 135 verbose: Whether to print details about the segmentation steps. By default, set to 'True'. 136 137 Returns: 138 Array with the volumetric segmentation. 139 Tuple with the first and last segmented slice. 140 """ 141 use_box, use_mask, use_points, use_single_point = _validate_projection(projection) 142 143 if update_progress is None: 144 def update_progress(*args): 145 pass 146 147 def segment_range(z_start, z_stop, increment, stopping_criterion, threshold=None, verbose=False): 148 z = z_start + increment 149 while True: 150 if verbose: 151 print(f"Segment {z_start} to {z_stop}: segmenting slice {z}") 152 seg_prev = segmentation[z - increment] 153 seg_z, score, _ = segment_from_mask( 154 predictor, seg_prev, image_embeddings=image_embeddings, i=z, use_mask=use_mask, 155 use_box=use_box, use_points=use_points, box_extension=box_extension, return_all=True, 156 use_single_point=use_single_point, 157 ) 158 if threshold is not None: 159 iou = util.compute_iou(seg_prev, seg_z) 160 if iou < threshold: 161 if verbose: 162 msg = f"Segmentation stopped at slice {z} due to IOU {iou} < {threshold}." 163 print(msg) 164 break 165 166 segmentation[z] = seg_z 167 z += increment 168 if stopping_criterion(z, z_stop): 169 if verbose: 170 print(f"Segment {z_start} to {z_stop}: stop at slice {z}") 171 break 172 update_progress(1) 173 174 return z - increment 175 176 z0, z1 = int(segmented_slices.min()), int(segmented_slices.max()) 177 178 # segment below the min slice 179 if z0 > 0 and not stop_lower: 180 z_min = segment_range(z0, 0, -1, np.less, iou_threshold, verbose=verbose) 181 else: 182 z_min = z0 183 184 # segment above the max slice 185 if z1 < segmentation.shape[0] - 1 and not stop_upper: 186 z_max = segment_range(z1, segmentation.shape[0] - 1, 1, np.greater, iou_threshold, verbose=verbose) 187 else: 188 z_max = z1 189 190 # segment in between min and max slice 191 if z0 != z1: 192 for z_start, z_stop in zip(segmented_slices[:-1], segmented_slices[1:]): 193 slice_diff = z_stop - z_start 194 z_mid = int((z_start + z_stop) // 2) 195 196 if slice_diff == 1: # the slices are adjacent -> we don't need to do anything 197 pass 198 199 elif z_start == z0 and stop_lower: # the lower slice is stop: we just segment from upper 200 segment_range(z_stop, z_start, -1, np.less_equal, verbose=verbose) 201 202 elif z_stop == z1 and stop_upper: # the upper slice is stop: we just segment from lower 203 segment_range(z_start, z_stop, 1, np.greater_equal, verbose=verbose) 204 205 elif slice_diff == 2: # there is only one slice in between -> use combined mask 206 z = z_start + 1 207 seg_prompt = np.logical_or(segmentation[z_start] == 1, segmentation[z_stop] == 1) 208 segmentation[z] = segment_from_mask( 209 predictor, seg_prompt, image_embeddings=image_embeddings, i=z, 210 use_mask=use_mask, use_box=use_box, use_points=use_points, 211 box_extension=box_extension 212 ) 213 update_progress(1) 214 215 else: # there is a range of more than 2 slices in between -> segment ranges 216 # segment from bottom 217 segment_range( 218 z_start, z_mid, 1, np.greater_equal if slice_diff % 2 == 0 else np.greater, verbose=verbose 219 ) 220 # segment from top 221 segment_range(z_stop, z_mid, -1, np.less_equal, verbose=verbose) 222 # if the difference between start and stop is even, 223 # then we have a slice in the middle that is the same distance from top bottom 224 # in this case the slice is not segmented in the ranges above, and we segment it 225 # using the combined mask from the adjacent top and bottom slice as prompt 226 if slice_diff % 2 == 0: 227 seg_prompt = np.logical_or(segmentation[z_mid - 1] == 1, segmentation[z_mid + 1] == 1) 228 segmentation[z_mid] = segment_from_mask( 229 predictor, seg_prompt, image_embeddings=image_embeddings, i=z_mid, 230 use_mask=use_mask, use_box=use_box, use_points=use_points, 231 box_extension=box_extension 232 ) 233 update_progress(1) 234 235 return segmentation, (z_min, z_max) 236 237 238def _preprocess_closing(slice_segmentation, gap_closing, pbar_update): 239 binarized = slice_segmentation > 0 240 # Use a structuring element that only closes elements in z, to avoid merging objects in-plane. 241 structuring_element = np.zeros((3, 1, 1)) 242 structuring_element[:, 0, 0] = 1 243 closed_segmentation = binary_closing(binarized, iterations=gap_closing, structure=structuring_element) 244 245 new_segmentation = np.zeros_like(slice_segmentation) 246 n_slices = new_segmentation.shape[0] 247 248 def process_slice(z, offset): 249 seg_z = slice_segmentation[z] 250 251 # Closing does not work for the first and last gap slices 252 if z < gap_closing or z >= (n_slices - gap_closing): 253 seg_z, _, _ = relabel_sequential(seg_z, offset=offset) 254 offset = int(seg_z.max()) + 1 255 return seg_z, offset 256 257 # Apply connected components to the closed segmentation. 258 closed_z = label(closed_segmentation[z]) 259 260 # Map objects in the closed and initial segmentation. 261 # We take objects from the closed segmentation unless they 262 # have overlap with more than one object from the initial segmentation. 263 # This indicates wrong merging of closeby objects that we want to prevent. 264 matches = segmentation_overlap(closed_z, seg_z) 265 matches = { 266 seg_id: matches.overlaps_for_label_a(seg_id)["label"] for seg_id in range(1, int(closed_z.max() + 1)) 267 } 268 matches = {k: v[v != 0] for k, v in matches.items()} 269 270 ids_initial, ids_closed = [], [] 271 for seg_id, matched in matches.items(): 272 if len(matched) > 1: 273 ids_initial.extend(matched.tolist()) 274 else: 275 ids_closed.append(seg_id) 276 277 seg_new = np.zeros_like(seg_z) 278 closed_mask = np.isin(closed_z, ids_closed) 279 seg_new[closed_mask] = closed_z[closed_mask] 280 281 if ids_initial: 282 initial_mask = np.isin(seg_z, ids_initial) 283 seg_new[initial_mask] = relabel_sequential(seg_z[initial_mask], offset=seg_new.max() + 1)[0] 284 285 seg_new, _, _ = relabel_sequential(seg_new, offset=offset) 286 max_z = seg_new.max() 287 if max_z > 0: 288 offset = int(max_z) + 1 289 290 return seg_new, offset 291 292 # Further optimization: parallelize 293 offset = 1 294 for z in range(n_slices): 295 new_segmentation[z], offset = process_slice(z, offset) 296 pbar_update(1) 297 298 return new_segmentation 299 300 301def _filter_z_extent(segmentation, min_z_extent): 302 props = regionprops(segmentation) 303 filter_ids = [] 304 for prop in props: 305 box = prop.bbox 306 z_extent = box[3] - box[0] 307 if z_extent < min_z_extent: 308 filter_ids.append(prop.label) 309 if filter_ids: 310 segmentation[np.isin(segmentation, filter_ids)] = 0 311 return segmentation 312 313 314def merge_instance_segmentation_3d( 315 slice_segmentation: np.ndarray, 316 beta: float = 0.5, 317 with_background: bool = True, 318 gap_closing: Optional[int] = None, 319 min_z_extent: Optional[int] = None, 320 verbose: bool = True, 321 pbar_init: Optional[callable] = None, 322 pbar_update: Optional[callable] = None, 323) -> np.ndarray: 324 """Merge stacked 2d instance segmentations into a consistent 3d segmentation. 325 326 Solves a multicut problem based on the overlap of objects to merge across z. 327 328 Args: 329 slice_segmentation: The stacked segmentation across the slices. 330 We assume that the segmentation is labeled consecutive across z. 331 beta: The bias term for the multicut. Higher values lead to a larger 332 degree of over-segmentation and vice versa. by default, set to '0.5'. 333 with_background: Whether this is a segmentation problem with background. 334 In that case all edges connecting to the background are set to be repulsive. 335 By default, set to 'True'. 336 gap_closing: If given, gaps in the segmentation are closed with a binary closing 337 operation. The value is used to determine the number of iterations for the closing. 338 min_z_extent: Require a minimal extent in z for the segmented objects. 339 This can help to prevent segmentation artifacts. 340 verbose: Verbosity flag. By default, set to 'True'. 341 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 342 Can be used together with pbar_update to handle napari progress bar in other thread. 343 To enable using this function within a threadworker. 344 pbar_update: Callback to update an external progress bar. 345 346 Returns: 347 The merged segmentation. 348 """ 349 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 350 351 if gap_closing is not None and gap_closing > 0: 352 pbar_init(slice_segmentation.shape[0] + 1, "Merge segmentation") 353 slice_segmentation = _preprocess_closing(slice_segmentation, gap_closing, pbar_update) 354 else: 355 pbar_init(1, "Merge segmentation") 356 357 # Extract the overlap between slices. 358 edges = track_utils.compute_edges_from_overlap(slice_segmentation, verbose=False) 359 if len(edges) == 0: # Nothing to merge. 360 return slice_segmentation 361 362 uv_ids = np.array([[edge["source"], edge["target"]] for edge in edges], dtype=np.uint64) 363 overlaps = np.array([edge["score"] for edge in edges]) 364 365 n_nodes = int(slice_segmentation.max() + 1) 366 graph = UndirectedGraph(n_nodes) 367 graph.insert_edges(uv_ids) 368 369 costs = seg_utils.multicut.compute_edge_costs(overlaps) 370 # Set background weights to be maximally repulsive. 371 if with_background: 372 bg_edges = (uv_ids == 0).any(axis=1) 373 costs[bg_edges] = -8.0 374 375 node_labels = seg_utils.multicut.multicut_decomposition(graph, 1.0 - costs, beta=beta) 376 377 segmentation = node_labels[slice_segmentation] 378 if min_z_extent is not None and min_z_extent > 0: 379 segmentation = _filter_z_extent(segmentation, min_z_extent) 380 381 pbar_update(1) 382 pbar_close() 383 384 return segmentation 385 386 387def _segment_slices( 388 data, predictor, segmentor, embedding_path, verbose, tile_shape, halo, batch_size=1, **kwargs 389): 390 assert data.ndim == 3 391 392 image_embeddings = precompute_image_embeddings( 393 predictor=predictor, 394 input_=data, 395 save_path=embedding_path, 396 ndim=3, 397 tile_shape=tile_shape, 398 halo=halo, 399 verbose=verbose, 400 batch_size=batch_size, 401 ) 402 403 offset = 0 404 segmentation = np.zeros(data.shape, dtype="uint32") 405 406 for i in util._progress_bar(range(segmentation.shape[0]), desc="Segment slices", disable=not verbose): 407 segmentor.initialize(data[i], image_embeddings=image_embeddings, verbose=False, i=i) 408 seg = segmentor.generate(**kwargs) 409 410 # Set offset for instance per slice. 411 max_z = int(seg.max()) 412 if max_z == 0: 413 continue 414 seg[seg != 0] += offset 415 offset = max_z + offset 416 segmentation[i] = seg 417 418 return segmentation, image_embeddings 419 420 421def automatic_3d_segmentation( 422 volume: np.ndarray, 423 predictor: SamPredictor, 424 segmentor: AutoSegBase, 425 embedding_path: Optional[Union[str, os.PathLike]] = None, 426 with_background: bool = True, 427 gap_closing: Optional[int] = None, 428 min_z_extent: Optional[int] = None, 429 tile_shape: Optional[Tuple[int, int]] = None, 430 halo: Optional[Tuple[int, int]] = None, 431 verbose: bool = True, 432 return_embeddings: bool = False, 433 batch_size: int = 1, 434 **kwargs, 435) -> np.ndarray: 436 """Automatically segment objects in a volume. 437 438 First segments slices individually in 2d and then merges them across 3d 439 based on overlap of objects between slices. 440 441 Args: 442 volume: The input volume. 443 predictor: The Segment Anything predictor. 444 segmentor: The instance segmentation class. 445 embedding_path: The path to save pre-computed embeddings. 446 with_background: Whether the segmentation has background. By default, set to 'True'. 447 gap_closing: If given, gaps in the segmentation are closed with a binary closing 448 operation. The value is used to determine the number of iterations for the closing. 449 min_z_extent: Require a minimal extent in z for the segmented objects. 450 This can help to prevent segmentation artifacts. 451 tile_shape: Shape of the tiles for tiled prediction. By default prediction is run without tiling. 452 halo: Overlap of the tiles for tiled prediction. By default prediction is run without tiling. 453 verbose: Verbosity flag. By default, set to 'True'. 454 return_embeddings: Whether to return the precomputed image embeddings. By default, set to 'False'. 455 batch_size: The batch size to compute image embeddings over planes. By default, set to '1'. 456 kwargs: Keyword arguments for the 'generate' method of the 'segmentor'. 457 458 Returns: 459 The segmentation. 460 """ 461 segmentation, image_embeddings = _segment_slices( 462 data=volume, 463 predictor=predictor, 464 segmentor=segmentor, 465 embedding_path=embedding_path, 466 verbose=verbose, 467 tile_shape=tile_shape, 468 halo=halo, 469 batch_size=batch_size, 470 **kwargs 471 ) 472 segmentation = merge_instance_segmentation_3d( 473 segmentation, 474 beta=0.5, 475 with_background=with_background, 476 gap_closing=gap_closing, 477 min_z_extent=min_z_extent, 478 verbose=verbose, 479 ) 480 if return_embeddings: 481 return segmentation, image_embeddings 482 else: 483 return segmentation 484 485 486def _require_trackastra(): 487 """Raise if trackastra is unavailable, naming what actually went wrong. 488 489 Trackastra being absent and trackastra failing to import because one of its dependencies is 490 broken look the same here, but only the first is fixed by installing trackastra. 491 492 Raises: 493 RuntimeError: If trackastra could not be imported. 494 """ 495 if Trackastra is not None: 496 return 497 498 # A broken dependency raises a plain ImportError, which does not say which package is missing. 499 if find_spec("trackastra") is None: 500 message = "Automatic tracking requires trackastra. You can install it via 'pip install trackastra'." 501 else: 502 cause = str(TRACKASTRA_IMPORT_ERROR).strip().splitlines() 503 cause = cause[0] if cause else type(TRACKASTRA_IMPORT_ERROR).__name__ 504 message = ( 505 f"Automatic tracking requires trackastra, which is installed but fails to import: {cause}. " 506 "One of its dependencies is missing or incompatible, so reinstalling trackastra will not " 507 "fix this. See the traceback above for the failing import." 508 ) 509 raise RuntimeError(message) from TRACKASTRA_IMPORT_ERROR 510 511 512def _filter_tracks(tracking_result, min_track_length): 513 props = regionprops(tracking_result) 514 discard_ids = [] 515 for prop in props: 516 label_id = prop.label 517 # The first axis of the tracking result is time, so the bbox extent along it is the track length. 518 t_start, t_stop = prop.bbox[0], prop.bbox[3] 519 if t_stop - t_start < min_track_length: 520 discard_ids.append(label_id) 521 tracking_result = tracking_result.copy() 522 tracking_result[np.isin(tracking_result, discard_ids)] = 0 523 # We deliberately do not relabel the result here, so that the remaining track ids stay consistent with 524 # the lineage information. Non-consecutive track ids are filtered from the lineages via '_filter_lineages'. 525 return tracking_result 526 527 528def _extract_tracks_and_lineages(segmentations, track_data, parent_graph): 529 # The track data has the following layout: n_tracks x 4 530 # With the following columns: 531 # track_id - id of the track (= result from trackastra) 532 # timepoint 533 # y coordinate 534 # x coordinate 535 536 # Use the last three columns to index the segmentation and get the segmentation id. 537 index = np.round(track_data[:, 1:], 0).astype("int32") 538 index = tuple(index[:, i] for i in range(index.shape[1])) 539 segmentation_ids = segmentations[index] 540 541 # Find the mapping of nodes (= segmented objects) to track-ids. 542 track_ids = track_data[:, 0].astype("int32") 543 assert len(segmentation_ids) == len(track_ids) 544 node_to_track = {k: v for k, v in zip(segmentation_ids, track_ids)} 545 546 # Find the lineages as connected components in the parent graph. 547 # First, we build a proper graph. 548 lineage_graph = nx.Graph() 549 for k, v in parent_graph.items(): 550 lineage_graph.add_edge(k, v) 551 552 # Then, find the connected components, and compute the lineage representation expected by micro-sam from it: 553 # E.g. if we have three lineages, the first consisting of three tracks and the second and third of one track each: 554 # [ 555 # {1: [2, 3]}, lineage with a dividing cell 556 # {4: []}, lineage with just one cell 557 # {5: []}, lineage with just one cell 558 # ] 559 560 # Determine the first time point of each track, so that we can orient each lineage tree by time. 561 # The parent_graph is undirected here, so we root each component at its temporally earliest track. 562 # Otherwise the parent / child orientation would be arbitrary and could be temporally invalid 563 # (a 'parent' appearing only after its 'child'), which breaks downstream consumers like CTC, GEFF 564 # and TrackMate export as well as the napari lineage display. 565 track_first_time = {} 566 for track_id, t in zip(track_ids.tolist(), track_data[:, 1].astype("int32").tolist()): 567 if track_id not in track_first_time or t < track_first_time[track_id]: 568 track_first_time[track_id] = t 569 570 # First, we fill the lineages which have one or more divisions, i.e. trees with more than one node. 571 lineages = [] 572 for component in nx.connected_components(lineage_graph): 573 root = min(component, key=lambda node: track_first_time.get(node, 0)) 574 lineage_dict = {} 575 576 def dfs(node, parent): 577 # Avoid revisiting the parent node 578 children = [n for n in lineage_graph[node] if n != parent] 579 lineage_dict[node] = children 580 for child in children: 581 dfs(child, node) 582 583 dfs(root, None) 584 lineages.append(lineage_dict) 585 586 # Then add single node lineages, which are not reflected in the original graph. 587 all_tracks = set(track_ids.tolist()) 588 lineage_tracks = [] 589 for lineage in lineages: 590 for k, v in lineage.items(): 591 lineage_tracks.append(k) 592 lineage_tracks.extend(v) 593 singleton_tracks = list(all_tracks - set(lineage_tracks)) 594 lineages.extend([{track: []} for track in singleton_tracks]) 595 596 # Make sure node_to_track contains everything. 597 all_seg_ids = np.unique(segmentations) 598 missing_seg_ids = np.setdiff1d(all_seg_ids, list(node_to_track.keys())) 599 node_to_track.update({seg_id: 0 for seg_id in missing_seg_ids}) 600 return node_to_track, lineages 601 602 603def _filter_lineages(lineages, tracking_result): 604 track_ids = set(np.unique(tracking_result)) - {0} 605 filtered_lineages = [] 606 for lineage in lineages: 607 # Drop nodes that are no longer present, both as parents (keys) and as children (values), 608 # so that the lineage does not reference filtered-out tracks. 609 filtered_lineage = { 610 k: [c for c in v if c in track_ids] for k, v in lineage.items() if k in track_ids 611 } 612 if filtered_lineage: 613 filtered_lineages.append(filtered_lineage) 614 return filtered_lineages 615 616 617def _tracking_impl(timeseries, segmentation, mode, min_time_extent, tracking_model="general_2d", output_folder=None): 618 device = "cuda" if torch.cuda.is_available() else "cpu" 619 download_dir = util.get_model_cache_directory("trackastra") 620 model = Trackastra.from_pretrained(tracking_model, device=device, download_dir=download_dir) 621 result = model.track(timeseries, segmentation, mode=mode) 622 try: 623 lineage_graph, _ = result 624 except ValueError: 625 lineage_graph = result 626 627 track_data, parent_graph, _ = graph_to_napari_tracks(lineage_graph) 628 if track_data.size == 0: 629 warnings.warn("Tracking result is empty.") 630 tracking_result = np.zeros_like(segmentation) 631 lineages = [] 632 return tracking_result, lineages 633 634 node_to_track, lineages = _extract_tracks_and_lineages(segmentation, track_data, parent_graph) 635 tracking_result = recolor_segmentation(segmentation, node_to_track) 636 637 if output_folder is not None: # Store tracking results in CTC format. 638 graph_to_ctc(lineage_graph, segmentation, outdir=output_folder) 639 640 # Filter out short tracks. Trackastra has no native option for this, so we do it as a post-process. 641 if min_time_extent is not None and min_time_extent > 0: 642 tracking_result = _filter_tracks(tracking_result, min_time_extent) 643 644 # Filter out pruned lineages. 645 # May either be missing due to track filtering or non-consecutive track numbering in trackastra. 646 lineages = _filter_lineages(lineages, tracking_result) 647 648 return tracking_result, lineages 649 650 651def track_across_frames( 652 timeseries: np.ndarray, 653 segmentation: np.ndarray, 654 gap_closing: Optional[int] = None, 655 min_time_extent: Optional[int] = None, 656 mode: str = "greedy", 657 tracking_model: str = "general_2d", 658 verbose: bool = True, 659 pbar_init: Optional[callable] = None, 660 pbar_update: Optional[callable] = None, 661 output_folder: Optional[Union[os.PathLike, str]] = None, 662) -> Tuple[np.ndarray, List[Dict]]: 663 """Track segmented objects over time. 664 665 This function uses Trackastra: https://www.ecva.net/papers/eccv_2024/papers_ECCV/papers/09819.pdf 666 for tracking. Please cite it if you use the automated tracking functionality. 667 668 Args: 669 timeseries: The input timeseries of images. 670 segmentation: The segmentation. Expect segmentation results per frame 671 that are relabeled so that segmentation ids don't overlap. 672 gap_closing: If given, gaps in the segmentation are closed with a binary closing 673 operation. The value is used to determine the number of iterations for the closing. 674 min_time_extent: Require a minimal extent in time for the tracked objects. 675 mode: The trackastra linking solver. One of 'greedy_nodiv', 'greedy' or 'ilp'. 676 'ilp' uses the motile solver. By default, set to 'greedy'. 677 tracking_model: The pretrained trackastra model to use. By default, set to 'general_2d'. 678 verbose: Verbosity flag. By default, set to 'True'. 679 pbar_init: Function to initialize the progress bar. 680 pbar_update: Function to update the progress bar. 681 output_folder: The folder where the tracking results are stored in CTC format. 682 683 Returns: 684 The tracking result. Each object is colored by its track id. 685 The lineages, which correspond to the cell divisions. Lineages are represented by a list of dicts, 686 with each dict encoding a lineage, where keys correspond to parent track ids. 687 Each key either maps to a list with two child track ids (cell division) or to an empty list (no division). 688 """ 689 _require_trackastra() 690 691 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init=pbar_init, pbar_update=pbar_update) 692 693 if gap_closing is not None and gap_closing > 0: 694 segmentation = _preprocess_closing(segmentation, gap_closing, pbar_update) 695 696 segmentation, lineage = _tracking_impl( 697 timeseries=np.asarray(timeseries), 698 segmentation=segmentation, 699 mode=mode, 700 min_time_extent=min_time_extent, 701 tracking_model=tracking_model, 702 output_folder=output_folder, 703 ) 704 return segmentation, lineage 705 706 707def automatic_tracking_implementation( 708 timeseries: np.ndarray, 709 predictor: SamPredictor, 710 segmentor: AutoSegBase, 711 embedding_path: Optional[Union[str, os.PathLike]] = None, 712 gap_closing: Optional[int] = None, 713 min_time_extent: Optional[int] = None, 714 mode: str = "greedy", 715 tracking_model: str = "general_2d", 716 tile_shape: Optional[Tuple[int, int]] = None, 717 halo: Optional[Tuple[int, int]] = None, 718 verbose: bool = True, 719 return_embeddings: bool = False, 720 batch_size: int = 1, 721 output_folder: Optional[Union[os.PathLike, str]] = None, 722 **kwargs, 723) -> Tuple[np.ndarray, List[Dict]]: 724 """Automatically track objects in a timesries based on per-frame automatic segmentation. 725 726 This function uses Trackastra: https://www.ecva.net/papers/eccv_2024/papers_ECCV/papers/09819.pdf 727 for tracking. Please cite it if you use the automated tracking functionality. 728 729 Args: 730 timeseries: The input timeseries of images. 731 predictor: The SAM model. 732 segmentor: The instance segmentation class. 733 embedding_path: The path to save pre-computed embeddings. 734 gap_closing: If given, gaps in the segmentation are closed with a binary closing 735 operation. The value is used to determine the number of iterations for the closing. 736 min_time_extent: Require a minimal extent in time for the tracked objects. 737 mode: The trackastra linking solver. One of 'greedy_nodiv', 'greedy' or 'ilp'. 738 'ilp' uses the motile solver. By default, set to 'greedy'. 739 tracking_model: The pretrained trackastra model to use. By default, set to 'general_2d'. 740 tile_shape: Shape of the tiles for tiled prediction. By default prediction is run without tiling. 741 halo: Overlap of the tiles for tiled prediction. By default prediction is run without tiling. 742 verbose: Verbosity flag. By default, set to 'True'. 743 return_embeddings: Whether to return the precomputed image embeddings. By default, set to 'False'. 744 batch_size: The batch size to compute image embeddings over planes. By default, set to '1'. 745 output_folder: The folder where the tracking results are stored in CTC format. 746 kwargs: Keyword arguments for the 'generate' method of the 'segmentor'. 747 748 Returns: 749 The tracking result. Each object is colored by its track id. 750 The lineages, which correspond to the cell divisions. Lineages are represented by a list of dicts, 751 with each dict encoding a lineage, where keys correspond to parent track ids. 752 Each key either maps to a list with two child track ids (cell division) or to an empty list (no division). 753 """ 754 _require_trackastra() 755 756 segmentation, image_embeddings = _segment_slices( 757 timeseries, predictor, segmentor, embedding_path, verbose, 758 tile_shape=tile_shape, halo=halo, batch_size=batch_size, 759 **kwargs, 760 ) 761 762 segmentation, lineage = track_across_frames( 763 timeseries=timeseries, 764 segmentation=segmentation, 765 gap_closing=gap_closing, 766 min_time_extent=min_time_extent, 767 mode=mode, 768 tracking_model=tracking_model, 769 verbose=verbose, 770 output_folder=output_folder, 771 ) 772 773 if return_embeddings: 774 return segmentation, lineage, image_embeddings 775 else: 776 return segmentation, lineage 777 778 779def get_napari_track_data( 780 segmentation: np.ndarray, lineages: List[Dict], n_threads: Optional[int] = None 781) -> Tuple[np.ndarray, Dict[int, List]]: 782 """Derive the inputs for the napari tracking layer from a tracking result. 783 784 Args: 785 segmentation: The segmentation, after relabeling with track ids. 786 lineages: The lineage information. 787 n_threads: Number of threads for extracting the track data from the segmentation. 788 789 Returns: 790 The array with the track data expected by napari. 791 The parent dictionary for napari. 792 """ 793 if n_threads is None: 794 n_threads = mp.cpu_count() 795 796 def compute_props(t): 797 props = regionprops(segmentation[t]) 798 # Create the track data representation for napari, which expects: 799 # track_id, timepoint, y, x 800 track_data = np.array([[prop.label, t] + list(prop.centroid) for prop in props]) 801 return track_data 802 803 with futures.ThreadPoolExecutor(n_threads) as tp: 804 track_data = list(tp.map(compute_props, range(segmentation.shape[0]))) 805 track_data = [data for data in track_data if data.size > 0] 806 # The segmentation can be empty, e.g. if 'min_time_extent' filtered out all tracks. 807 track_data = np.concatenate(track_data) if track_data else np.zeros((0, 4), dtype="float64") 808 809 # The graph representation of napari uses the children as keys and the parents as values, 810 # whereas our representation uses parents as keys and children as values. 811 # Hence, we need to translate the representation. 812 parent_graph = { 813 child: [parent] for lineage in lineages for parent, children in lineage.items() for child in children 814 } 815 816 return track_data, parent_graph 817 818 819def export_tracking_result_to_ctc( 820 segmentation: np.ndarray, 821 lineages: List[Dict], 822 output_folder: Union[os.PathLike, str], 823) -> None: 824 """Export a tracking result to the Cell Tracking Challenge (CTC) format. 825 826 This writes the standard CTC folder layout into 'output_folder': 827 - 'TRA/man_track.txt', the lineage file with one space-separated row 'L B E P' per track 828 (track id, first frame, last frame, parent track id, where the parent is 0 if the track has no parent). 829 - 'TRA/man_track<frame>.tif', the per-frame tracking masks, with each object labeled by its track id. 830 - 'SEG/man_seg<frame>.tif', the per-frame segmentation masks. 831 832 Args: 833 segmentation: The tracking result of shape (T, Y, X), with each object labeled by its track id. 834 lineages: The lineage information, a list of dicts mapping each parent track id to its child track ids. 835 output_folder: The folder where the CTC results are written, with 'TRA' and 'SEG' subfolders. 836 """ 837 if segmentation.ndim != 3: 838 raise ValueError(f"Expected a 3d (T, Y, X) tracking result, got shape {segmentation.shape}.") 839 840 tra_folder = os.path.join(output_folder, "TRA") 841 seg_folder = os.path.join(output_folder, "SEG") 842 os.makedirs(tra_folder, exist_ok=True) 843 os.makedirs(seg_folder, exist_ok=True) 844 845 # Map each child track to its parent track. Tracks without a parent get 0, as expected by the CTC format. 846 child_to_parent = {} 847 for lineage in lineages: 848 for parent, children in lineage.items(): 849 for child in children: 850 child_to_parent[child] = parent 851 852 # Determine the first and last frame in which each track id is present. 853 n_frames = segmentation.shape[0] 854 first_frame, last_frame = {}, {} 855 for t in range(n_frames): 856 for label_id in np.unique(segmentation[t]): 857 label_id = int(label_id) 858 if label_id == 0: 859 continue 860 if label_id not in first_frame: 861 first_frame[label_id] = t 862 last_frame[label_id] = t 863 864 # Write the lineage file into the tracking folder. 865 with open(os.path.join(tra_folder, "man_track.txt"), "w") as f: 866 for label_id in sorted(first_frame.keys()): 867 parent = child_to_parent.get(label_id, 0) 868 f.write(f"{label_id} {first_frame[label_id]} {last_frame[label_id]} {parent}\n") 869 870 # Write the per-frame masks, using uint16 if the track ids fit and uint32 otherwise. 871 # The tracking masks (TRA) and segmentation masks (SEG) share the same track-id labeling. 872 max_id = int(segmentation.max()) 873 dtype = "uint16" if max_id < np.iinfo("uint16").max else "uint32" 874 n_digits = max(4, len(str(n_frames - 1))) 875 for t in range(n_frames): 876 frame = segmentation[t].astype(dtype) 877 imageio.imwrite(os.path.join(tra_folder, f"man_track{t:0{n_digits}d}.tif"), frame) 878 imageio.imwrite(os.path.join(seg_folder, f"man_seg{t:0{n_digits}d}.tif"), frame) 879 880 881def _validate_tracking_result(segmentation): 882 if segmentation.ndim not in (3, 4): 883 raise ValueError( 884 f"Expected a tracking result with shape (T, Y, X) or (T, Z, Y, X), got shape {segmentation.shape}." 885 ) 886 887 888def _child_to_parent(lineages): 889 child_to_parent = {} 890 for lineage in lineages: 891 for parent, children in lineage.items(): 892 for child in children: 893 child_to_parent[int(child)] = int(parent) 894 return child_to_parent 895 896 897def _equivalent_radius(area, ndim): 898 if ndim == 2: 899 return float(np.sqrt(area / np.pi)) 900 return float(((3.0 * area) / (4.0 * np.pi)) ** (1.0 / 3.0)) 901 902 903def _tracking_result_to_graph(segmentation, lineages): 904 _validate_tracking_result(segmentation) 905 906 graph = nx.DiGraph() 907 records = [] 908 nodes_by_track = defaultdict(list) 909 spatial_ndim = segmentation.ndim - 1 910 911 for t, frame in enumerate(segmentation): 912 for prop in regionprops(frame): 913 node_id = len(records) 914 track_id = int(prop.label) 915 coords = tuple(float(coord) for coord in prop.centroid) 916 area = float(prop.area) 917 radius = _equivalent_radius(area, spatial_ndim) 918 record = { 919 "node_id": node_id, 920 "track_id": track_id, 921 "time": int(t), 922 "coords": coords, 923 "area": area, 924 "radius": radius, 925 } 926 records.append(record) 927 nodes_by_track[track_id].append(node_id) 928 graph.add_node( 929 node_id, 930 label=track_id, 931 track_id=track_id, 932 time=int(t), 933 coords=coords, 934 area=area, 935 radius=radius, 936 ) 937 938 if not records: 939 raise ValueError("Cannot export an empty tracking result.") 940 941 records_by_node = {record["node_id"]: record for record in records} 942 943 for track_nodes in nodes_by_track.values(): 944 track_nodes.sort(key=lambda node_id: records_by_node[node_id]["time"]) 945 for source, target in zip(track_nodes[:-1], track_nodes[1:]): 946 graph.add_edge(source, target, weight=1.0) 947 948 for child, parent in _child_to_parent(lineages).items(): 949 parent_nodes = nodes_by_track.get(parent, []) 950 child_nodes = nodes_by_track.get(child, []) 951 if not parent_nodes or not child_nodes: 952 continue 953 954 first_child = min(child_nodes, key=lambda node_id: records_by_node[node_id]["time"]) 955 child_start = records_by_node[first_child]["time"] 956 parent_candidates = [ 957 node_id for node_id in parent_nodes if records_by_node[node_id]["time"] < child_start 958 ] 959 if not parent_candidates: 960 warnings.warn( 961 f"Could not add lineage edge from parent track {parent} to child track {child}: " 962 "the parent has no detection before the child starts.", 963 stacklevel=2, 964 ) 965 continue 966 967 last_parent = max(parent_candidates, key=lambda node_id: records_by_node[node_id]["time"]) 968 graph.add_edge(last_parent, first_child, weight=1.0, division=True) 969 970 return graph, records, records_by_node 971 972 973def _normalize_output_path(output_path, default_name, suffix): 974 output_path = Path(output_path) 975 if output_path.suffix.lower() != suffix: 976 output_path = output_path / default_name 977 output_path.parent.mkdir(parents=True, exist_ok=True) 978 return output_path 979 980 981def export_tracking_result_to_geff( 982 segmentation: np.ndarray, 983 lineages: List[Dict], 984 output_path: Union[os.PathLike, str], 985) -> Path: 986 """Export a tracking result to GEFF. 987 988 The export follows the Trackastra GEFF layout: a zarr group containing the tracking masks in 989 'segmentation' and the graph in 'tracking_graph.geff'. 990 991 Args: 992 segmentation: The tracking result of shape (T, Y, X), with each object labeled by its track id. 993 lineages: The lineage information, a list of dicts mapping each parent track id to its child track ids. 994 output_path: The zarr path to write to. If a directory is passed, 'tracking_result.zarr' is written in it. 995 996 Returns: 997 The path of the written zarr group. 998 """ 999 try: 1000 from trackastra.tracking import write_to_geff 1001 except ImportError as e: 1002 raise RuntimeError( 1003 "GEFF export requires trackastra with GEFF support. Install a recent trackastra/geff version." 1004 ) from e 1005 1006 output_path = _normalize_output_path(output_path, "tracking_result.zarr", ".zarr") 1007 graph, _, _ = _tracking_result_to_graph(segmentation, lineages) 1008 write_to_geff(graph, segmentation, output_path) 1009 return output_path 1010 1011 1012def _format_float(value): 1013 return f"{float(value):.6f}" 1014 1015 1016def _trackmate_xyz(record): 1017 coords = record["coords"] 1018 if len(coords) == 2: 1019 y, x = coords 1020 z = 0.0 1021 elif len(coords) == 3: 1022 z, y, x = coords 1023 else: 1024 raise ValueError(f"Expected 2d or 3d coordinates, got {coords}.") 1025 return x, y, z 1026 1027 1028def _add_feature(parent, feature, name, shortname, dimension, isint=False): 1029 ET.SubElement( 1030 parent, 1031 "Feature", 1032 { 1033 "feature": feature, 1034 "name": name, 1035 "shortname": shortname, 1036 "dimension": dimension, 1037 "isint": str(isint).lower(), 1038 }, 1039 ) 1040 1041 1042def _add_trackmate_feature_declarations(model): 1043 declarations = ET.SubElement(model, "FeatureDeclarations") 1044 1045 spot_features = ET.SubElement(declarations, "SpotFeatures") 1046 _add_feature(spot_features, "QUALITY", "Quality", "Quality", "QUALITY") 1047 _add_feature(spot_features, "POSITION_X", "X", "X", "POSITION") 1048 _add_feature(spot_features, "POSITION_Y", "Y", "Y", "POSITION") 1049 _add_feature(spot_features, "POSITION_Z", "Z", "Z", "POSITION") 1050 _add_feature(spot_features, "POSITION_T", "T", "T", "TIME") 1051 _add_feature(spot_features, "FRAME", "Frame", "Frame", "NONE", isint=True) 1052 _add_feature(spot_features, "RADIUS", "Radius", "R", "LENGTH") 1053 _add_feature(spot_features, "VISIBILITY", "Visibility", "Visibility", "NONE", isint=True) 1054 _add_feature(spot_features, "AREA", "Area", "Area", "AREA") 1055 _add_feature(spot_features, "TRACKLET_ID", "micro-sam tracklet id", "Tracklet id", "NONE", isint=True) 1056 1057 edge_features = ET.SubElement(declarations, "EdgeFeatures") 1058 _add_feature(edge_features, "SPOT_SOURCE_ID", "Source spot ID", "Source", "NONE", isint=True) 1059 _add_feature(edge_features, "SPOT_TARGET_ID", "Target spot ID", "Target", "NONE", isint=True) 1060 _add_feature(edge_features, "LINK_COST", "Link cost", "Cost", "COST") 1061 _add_feature(edge_features, "EDGE_TIME", "Edge time", "T", "TIME") 1062 _add_feature(edge_features, "EDGE_X_LOCATION", "Edge X", "X", "POSITION") 1063 _add_feature(edge_features, "EDGE_Y_LOCATION", "Edge Y", "Y", "POSITION") 1064 _add_feature(edge_features, "EDGE_Z_LOCATION", "Edge Z", "Z", "POSITION") 1065 _add_feature(edge_features, "VELOCITY", "Velocity", "V", "VELOCITY") 1066 1067 track_features = ET.SubElement(declarations, "TrackFeatures") 1068 _add_feature(track_features, "TRACK_ID", "Track ID", "ID", "NONE", isint=True) 1069 _add_feature(track_features, "TRACK_INDEX", "Track index", "Index", "NONE", isint=True) 1070 _add_feature(track_features, "NUMBER_SPOTS", "Number of spots", "N spots", "NONE", isint=True) 1071 _add_feature(track_features, "NUMBER_GAPS", "Number of gaps", "Gaps", "NONE", isint=True) 1072 _add_feature(track_features, "NUMBER_SPLITS", "Number of splits", "Splits", "NONE", isint=True) 1073 _add_feature(track_features, "NUMBER_MERGES", "Number of merges", "Merges", "NONE", isint=True) 1074 _add_feature(track_features, "TRACK_START", "Track start", "Start", "TIME") 1075 _add_feature(track_features, "TRACK_STOP", "Track stop", "Stop", "TIME") 1076 _add_feature(track_features, "TRACK_DURATION", "Track duration", "Duration", "TIME") 1077 _add_feature(track_features, "TRACK_X_LOCATION", "Track X", "X", "POSITION") 1078 _add_feature(track_features, "TRACK_Y_LOCATION", "Track Y", "Y", "POSITION") 1079 _add_feature(track_features, "TRACK_Z_LOCATION", "Track Z", "Z", "POSITION") 1080 1081 1082def _add_trackmate_spots(model, records): 1083 all_spots = ET.SubElement(model, "AllSpots", {"nspots": str(len(records))}) 1084 records_by_frame = defaultdict(list) 1085 for record in records: 1086 records_by_frame[record["time"]].append(record) 1087 1088 for frame in sorted(records_by_frame): 1089 spots_in_frame = ET.SubElement(all_spots, "SpotsInFrame", {"frame": str(frame)}) 1090 for record in sorted(records_by_frame[frame], key=lambda rec: rec["node_id"]): 1091 x, y, z = _trackmate_xyz(record) 1092 node_id = record["node_id"] 1093 ET.SubElement( 1094 spots_in_frame, 1095 "Spot", 1096 { 1097 "ID": str(node_id), 1098 "name": f"ID{node_id}", 1099 "QUALITY": "1.0", 1100 "POSITION_X": _format_float(x), 1101 "POSITION_Y": _format_float(y), 1102 "POSITION_Z": _format_float(z), 1103 "POSITION_T": _format_float(record["time"]), 1104 "FRAME": str(record["time"]), 1105 "RADIUS": _format_float(record["radius"]), 1106 "VISIBILITY": "1", 1107 "AREA": _format_float(record["area"]), 1108 "TRACKLET_ID": str(record["track_id"]), 1109 }, 1110 ) 1111 1112 1113def _component_track_attributes(graph, component, track_id, track_index, records_by_node): 1114 times = [records_by_node[node_id]["time"] for node_id in component] 1115 xyz = np.array([_trackmate_xyz(records_by_node[node_id]) for node_id in component], dtype="float64") 1116 n_gaps = 0 1117 for source, target in graph.subgraph(component).edges: 1118 dt = records_by_node[target]["time"] - records_by_node[source]["time"] 1119 n_gaps += max(0, int(dt) - 1) 1120 1121 return { 1122 "name": f"Track_{track_id}", 1123 "TRACK_ID": str(track_id), 1124 "TRACK_INDEX": str(track_index), 1125 "NUMBER_SPOTS": str(len(component)), 1126 "NUMBER_GAPS": str(n_gaps), 1127 "NUMBER_SPLITS": str(sum(1 for node_id in component if graph.out_degree(node_id) > 1)), 1128 "NUMBER_MERGES": str(sum(1 for node_id in component if graph.in_degree(node_id) > 1)), 1129 "TRACK_START": _format_float(min(times)), 1130 "TRACK_STOP": _format_float(max(times)), 1131 "TRACK_DURATION": _format_float(max(times) - min(times) + 1), 1132 "TRACK_X_LOCATION": _format_float(float(xyz[:, 0].mean())), 1133 "TRACK_Y_LOCATION": _format_float(float(xyz[:, 1].mean())), 1134 "TRACK_Z_LOCATION": _format_float(float(xyz[:, 2].mean())), 1135 } 1136 1137 1138def _edge_trackmate_attributes(source, target, records_by_node): 1139 source_record = records_by_node[source] 1140 target_record = records_by_node[target] 1141 sx, sy, sz = _trackmate_xyz(source_record) 1142 tx, ty, tz = _trackmate_xyz(target_record) 1143 dt = target_record["time"] - source_record["time"] 1144 distance = np.linalg.norm(np.array([tx - sx, ty - sy, tz - sz], dtype="float64")) 1145 velocity = 0.0 if dt <= 0 else distance / dt 1146 1147 return { 1148 "SPOT_SOURCE_ID": str(source), 1149 "SPOT_TARGET_ID": str(target), 1150 "LINK_COST": "0.0", 1151 "EDGE_TIME": _format_float((source_record["time"] + target_record["time"]) / 2.0), 1152 "EDGE_X_LOCATION": _format_float((sx + tx) / 2.0), 1153 "EDGE_Y_LOCATION": _format_float((sy + ty) / 2.0), 1154 "EDGE_Z_LOCATION": _format_float((sz + tz) / 2.0), 1155 "VELOCITY": _format_float(velocity), 1156 } 1157 1158 1159def _add_trackmate_tracks(model, graph, records_by_node): 1160 all_tracks = ET.SubElement(model, "AllTracks") 1161 filtered_tracks = ET.SubElement(model, "FilteredTracks") 1162 1163 def component_sort_key(component): 1164 return min(records_by_node[node_id]["time"] for node_id in component), min(component) 1165 1166 def edge_sort_key(edge): 1167 source, target = edge 1168 return records_by_node[source]["time"], source, records_by_node[target]["time"], target 1169 1170 components = list(nx.weakly_connected_components(graph)) 1171 components.sort(key=component_sort_key) 1172 1173 for track_index, component in enumerate(components): 1174 track_id = track_index 1175 track = ET.SubElement( 1176 all_tracks, 1177 "Track", 1178 _component_track_attributes(graph, component, track_id, track_index, records_by_node), 1179 ) 1180 edges = list(graph.subgraph(component).edges) 1181 edges.sort(key=edge_sort_key) 1182 for source, target in edges: 1183 ET.SubElement(track, "Edge", _edge_trackmate_attributes(source, target, records_by_node)) 1184 1185 ET.SubElement(filtered_tracks, "TrackID", {"TRACK_ID": str(track_id)}) 1186 1187 1188def _add_trackmate_settings(root, segmentation): 1189 settings = ET.SubElement(root, "Settings") 1190 spatial_shape = segmentation.shape[1:] 1191 if len(spatial_shape) == 2: 1192 height, width = spatial_shape 1193 nslices = 1 1194 else: 1195 nslices, height, width = spatial_shape 1196 1197 ET.SubElement( 1198 settings, 1199 "ImageData", 1200 { 1201 "filename": "", 1202 "folder": "", 1203 "width": str(width), 1204 "height": str(height), 1205 "nslices": str(nslices), 1206 "nframes": str(segmentation.shape[0]), 1207 "pixelwidth": "1.0", 1208 "pixelheight": "1.0", 1209 "voxeldepth": "1.0", 1210 "timeinterval": "1.0", 1211 }, 1212 ) 1213 ET.SubElement(settings, "InitialSpotFilter", {"feature": "QUALITY", "value": "0.0", "isabove": "true"}) 1214 ET.SubElement(settings, "SpotFilterCollection") 1215 ET.SubElement(settings, "TrackFilterCollection") 1216 ET.SubElement(settings, "AnalyzerCollection") 1217 1218 1219def export_tracking_result_to_trackmate_xml( 1220 segmentation: np.ndarray, 1221 lineages: List[Dict], 1222 output_path: Union[os.PathLike, str], 1223) -> Path: 1224 """Export a tracking result to TrackMate XML. 1225 1226 The XML contains all per-frame detections as TrackMate spots and the committed tracking graph as TrackMate tracks. 1227 1228 Args: 1229 segmentation: The tracking result of shape (T, Y, X), with each object labeled by its track id. 1230 lineages: The lineage information, a list of dicts mapping each parent track id to its child track ids. 1231 output_path: The XML path to write to. If a directory is passed, 'tracking_result.xml' is written in it. 1232 1233 Returns: 1234 The path of the written XML file. 1235 """ 1236 output_path = _normalize_output_path(output_path, "tracking_result.xml", ".xml") 1237 graph, records, records_by_node = _tracking_result_to_graph(segmentation, lineages) 1238 1239 root = ET.Element("TrackMate", {"version": "micro-sam"}) 1240 ET.SubElement(root, "Log").text = "Created by micro-sam." 1241 model = ET.SubElement(root, "Model", {"spatialunits": "pixel", "timeunits": "frame"}) 1242 _add_trackmate_feature_declarations(model) 1243 _add_trackmate_spots(model, records) 1244 _add_trackmate_tracks(model, graph, records_by_node) 1245 _add_trackmate_settings(root, segmentation) 1246 ET.SubElement(root, "GUIState", {"state": "ConfigureViews"}) 1247 ET.SubElement(root, "DisplaySettings") 1248 1249 tree = ET.ElementTree(root) 1250 ET.indent(tree, space=" ") 1251 tree.write(output_path, encoding="UTF-8", xml_declaration=True) 1252 return output_path
108def segment_mask_in_volume( 109 segmentation: np.ndarray, 110 predictor: SamPredictor, 111 image_embeddings: util.ImageEmbeddings, 112 segmented_slices: np.ndarray, 113 stop_lower: bool, 114 stop_upper: bool, 115 iou_threshold: float, 116 projection: Union[str, dict], 117 update_progress: Optional[callable] = None, 118 box_extension: float = 0.0, 119 verbose: bool = False, 120) -> Tuple[np.ndarray, Tuple[int, int]]: 121 """Segment an object mask in in volumetric data. 122 123 Args: 124 segmentation: The initial segmentation for the object. 125 predictor: The Segment Anything predictor. 126 image_embeddings: The precomputed image embeddings for the volume. 127 segmented_slices: List of slices for which this object has already been segmented. 128 stop_lower: Whether to stop at the lowest segmented slice. 129 stop_upper: Wheter to stop at the topmost segmented slice. 130 iou_threshold: The IOU threshold for continuing segmentation across 3d. 131 projection: The projection method to use. One of 'box', 'mask', 'points', 'points_and_mask' or 'single point'. 132 Pass a dictionary to choose the excact combination of projection modes. 133 update_progress: Callback to update an external progress bar. 134 box_extension: Extension factor for increasing the box size after projection. 135 By default, does not increase the projected box size. 136 verbose: Whether to print details about the segmentation steps. By default, set to 'True'. 137 138 Returns: 139 Array with the volumetric segmentation. 140 Tuple with the first and last segmented slice. 141 """ 142 use_box, use_mask, use_points, use_single_point = _validate_projection(projection) 143 144 if update_progress is None: 145 def update_progress(*args): 146 pass 147 148 def segment_range(z_start, z_stop, increment, stopping_criterion, threshold=None, verbose=False): 149 z = z_start + increment 150 while True: 151 if verbose: 152 print(f"Segment {z_start} to {z_stop}: segmenting slice {z}") 153 seg_prev = segmentation[z - increment] 154 seg_z, score, _ = segment_from_mask( 155 predictor, seg_prev, image_embeddings=image_embeddings, i=z, use_mask=use_mask, 156 use_box=use_box, use_points=use_points, box_extension=box_extension, return_all=True, 157 use_single_point=use_single_point, 158 ) 159 if threshold is not None: 160 iou = util.compute_iou(seg_prev, seg_z) 161 if iou < threshold: 162 if verbose: 163 msg = f"Segmentation stopped at slice {z} due to IOU {iou} < {threshold}." 164 print(msg) 165 break 166 167 segmentation[z] = seg_z 168 z += increment 169 if stopping_criterion(z, z_stop): 170 if verbose: 171 print(f"Segment {z_start} to {z_stop}: stop at slice {z}") 172 break 173 update_progress(1) 174 175 return z - increment 176 177 z0, z1 = int(segmented_slices.min()), int(segmented_slices.max()) 178 179 # segment below the min slice 180 if z0 > 0 and not stop_lower: 181 z_min = segment_range(z0, 0, -1, np.less, iou_threshold, verbose=verbose) 182 else: 183 z_min = z0 184 185 # segment above the max slice 186 if z1 < segmentation.shape[0] - 1 and not stop_upper: 187 z_max = segment_range(z1, segmentation.shape[0] - 1, 1, np.greater, iou_threshold, verbose=verbose) 188 else: 189 z_max = z1 190 191 # segment in between min and max slice 192 if z0 != z1: 193 for z_start, z_stop in zip(segmented_slices[:-1], segmented_slices[1:]): 194 slice_diff = z_stop - z_start 195 z_mid = int((z_start + z_stop) // 2) 196 197 if slice_diff == 1: # the slices are adjacent -> we don't need to do anything 198 pass 199 200 elif z_start == z0 and stop_lower: # the lower slice is stop: we just segment from upper 201 segment_range(z_stop, z_start, -1, np.less_equal, verbose=verbose) 202 203 elif z_stop == z1 and stop_upper: # the upper slice is stop: we just segment from lower 204 segment_range(z_start, z_stop, 1, np.greater_equal, verbose=verbose) 205 206 elif slice_diff == 2: # there is only one slice in between -> use combined mask 207 z = z_start + 1 208 seg_prompt = np.logical_or(segmentation[z_start] == 1, segmentation[z_stop] == 1) 209 segmentation[z] = segment_from_mask( 210 predictor, seg_prompt, image_embeddings=image_embeddings, i=z, 211 use_mask=use_mask, use_box=use_box, use_points=use_points, 212 box_extension=box_extension 213 ) 214 update_progress(1) 215 216 else: # there is a range of more than 2 slices in between -> segment ranges 217 # segment from bottom 218 segment_range( 219 z_start, z_mid, 1, np.greater_equal if slice_diff % 2 == 0 else np.greater, verbose=verbose 220 ) 221 # segment from top 222 segment_range(z_stop, z_mid, -1, np.less_equal, verbose=verbose) 223 # if the difference between start and stop is even, 224 # then we have a slice in the middle that is the same distance from top bottom 225 # in this case the slice is not segmented in the ranges above, and we segment it 226 # using the combined mask from the adjacent top and bottom slice as prompt 227 if slice_diff % 2 == 0: 228 seg_prompt = np.logical_or(segmentation[z_mid - 1] == 1, segmentation[z_mid + 1] == 1) 229 segmentation[z_mid] = segment_from_mask( 230 predictor, seg_prompt, image_embeddings=image_embeddings, i=z_mid, 231 use_mask=use_mask, use_box=use_box, use_points=use_points, 232 box_extension=box_extension 233 ) 234 update_progress(1) 235 236 return segmentation, (z_min, z_max)
Segment an object mask in in volumetric data.
Arguments:
- segmentation: The initial segmentation for the object.
- predictor: The Segment Anything predictor.
- image_embeddings: The precomputed image embeddings for the volume.
- segmented_slices: List of slices for which this object has already been segmented.
- stop_lower: Whether to stop at the lowest segmented slice.
- stop_upper: Wheter to stop at the topmost segmented slice.
- iou_threshold: The IOU threshold for continuing segmentation across 3d.
- projection: The projection method to use. One of 'box', 'mask', 'points', 'points_and_mask' or 'single point'. Pass a dictionary to choose the excact combination of projection modes.
- update_progress: Callback to update an external progress bar.
- box_extension: Extension factor for increasing the box size after projection. By default, does not increase the projected box size.
- verbose: Whether to print details about the segmentation steps. By default, set to 'True'.
Returns:
Array with the volumetric segmentation. Tuple with the first and last segmented slice.
315def merge_instance_segmentation_3d( 316 slice_segmentation: np.ndarray, 317 beta: float = 0.5, 318 with_background: bool = True, 319 gap_closing: Optional[int] = None, 320 min_z_extent: Optional[int] = None, 321 verbose: bool = True, 322 pbar_init: Optional[callable] = None, 323 pbar_update: Optional[callable] = None, 324) -> np.ndarray: 325 """Merge stacked 2d instance segmentations into a consistent 3d segmentation. 326 327 Solves a multicut problem based on the overlap of objects to merge across z. 328 329 Args: 330 slice_segmentation: The stacked segmentation across the slices. 331 We assume that the segmentation is labeled consecutive across z. 332 beta: The bias term for the multicut. Higher values lead to a larger 333 degree of over-segmentation and vice versa. by default, set to '0.5'. 334 with_background: Whether this is a segmentation problem with background. 335 In that case all edges connecting to the background are set to be repulsive. 336 By default, set to 'True'. 337 gap_closing: If given, gaps in the segmentation are closed with a binary closing 338 operation. The value is used to determine the number of iterations for the closing. 339 min_z_extent: Require a minimal extent in z for the segmented objects. 340 This can help to prevent segmentation artifacts. 341 verbose: Verbosity flag. By default, set to 'True'. 342 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 343 Can be used together with pbar_update to handle napari progress bar in other thread. 344 To enable using this function within a threadworker. 345 pbar_update: Callback to update an external progress bar. 346 347 Returns: 348 The merged segmentation. 349 """ 350 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 351 352 if gap_closing is not None and gap_closing > 0: 353 pbar_init(slice_segmentation.shape[0] + 1, "Merge segmentation") 354 slice_segmentation = _preprocess_closing(slice_segmentation, gap_closing, pbar_update) 355 else: 356 pbar_init(1, "Merge segmentation") 357 358 # Extract the overlap between slices. 359 edges = track_utils.compute_edges_from_overlap(slice_segmentation, verbose=False) 360 if len(edges) == 0: # Nothing to merge. 361 return slice_segmentation 362 363 uv_ids = np.array([[edge["source"], edge["target"]] for edge in edges], dtype=np.uint64) 364 overlaps = np.array([edge["score"] for edge in edges]) 365 366 n_nodes = int(slice_segmentation.max() + 1) 367 graph = UndirectedGraph(n_nodes) 368 graph.insert_edges(uv_ids) 369 370 costs = seg_utils.multicut.compute_edge_costs(overlaps) 371 # Set background weights to be maximally repulsive. 372 if with_background: 373 bg_edges = (uv_ids == 0).any(axis=1) 374 costs[bg_edges] = -8.0 375 376 node_labels = seg_utils.multicut.multicut_decomposition(graph, 1.0 - costs, beta=beta) 377 378 segmentation = node_labels[slice_segmentation] 379 if min_z_extent is not None and min_z_extent > 0: 380 segmentation = _filter_z_extent(segmentation, min_z_extent) 381 382 pbar_update(1) 383 pbar_close() 384 385 return segmentation
Merge stacked 2d instance segmentations into a consistent 3d segmentation.
Solves a multicut problem based on the overlap of objects to merge across z.
Arguments:
- slice_segmentation: The stacked segmentation across the slices. We assume that the segmentation is labeled consecutive across z.
- beta: The bias term for the multicut. Higher values lead to a larger degree of over-segmentation and vice versa. by default, set to '0.5'.
- with_background: Whether this is a segmentation problem with background. In that case all edges connecting to the background are set to be repulsive. By default, set to 'True'.
- gap_closing: If given, gaps in the segmentation are closed with a binary closing operation. The value is used to determine the number of iterations for the closing.
- min_z_extent: Require a minimal extent in z for the segmented objects. This can help to prevent segmentation artifacts.
- verbose: Verbosity flag. By default, set to 'True'.
- pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. Can be used together with pbar_update to handle napari progress bar in other thread. To enable using this function within a threadworker.
- pbar_update: Callback to update an external progress bar.
Returns:
The merged segmentation.
422def automatic_3d_segmentation( 423 volume: np.ndarray, 424 predictor: SamPredictor, 425 segmentor: AutoSegBase, 426 embedding_path: Optional[Union[str, os.PathLike]] = None, 427 with_background: bool = True, 428 gap_closing: Optional[int] = None, 429 min_z_extent: Optional[int] = None, 430 tile_shape: Optional[Tuple[int, int]] = None, 431 halo: Optional[Tuple[int, int]] = None, 432 verbose: bool = True, 433 return_embeddings: bool = False, 434 batch_size: int = 1, 435 **kwargs, 436) -> np.ndarray: 437 """Automatically segment objects in a volume. 438 439 First segments slices individually in 2d and then merges them across 3d 440 based on overlap of objects between slices. 441 442 Args: 443 volume: The input volume. 444 predictor: The Segment Anything predictor. 445 segmentor: The instance segmentation class. 446 embedding_path: The path to save pre-computed embeddings. 447 with_background: Whether the segmentation has background. By default, set to 'True'. 448 gap_closing: If given, gaps in the segmentation are closed with a binary closing 449 operation. The value is used to determine the number of iterations for the closing. 450 min_z_extent: Require a minimal extent in z for the segmented objects. 451 This can help to prevent segmentation artifacts. 452 tile_shape: Shape of the tiles for tiled prediction. By default prediction is run without tiling. 453 halo: Overlap of the tiles for tiled prediction. By default prediction is run without tiling. 454 verbose: Verbosity flag. By default, set to 'True'. 455 return_embeddings: Whether to return the precomputed image embeddings. By default, set to 'False'. 456 batch_size: The batch size to compute image embeddings over planes. By default, set to '1'. 457 kwargs: Keyword arguments for the 'generate' method of the 'segmentor'. 458 459 Returns: 460 The segmentation. 461 """ 462 segmentation, image_embeddings = _segment_slices( 463 data=volume, 464 predictor=predictor, 465 segmentor=segmentor, 466 embedding_path=embedding_path, 467 verbose=verbose, 468 tile_shape=tile_shape, 469 halo=halo, 470 batch_size=batch_size, 471 **kwargs 472 ) 473 segmentation = merge_instance_segmentation_3d( 474 segmentation, 475 beta=0.5, 476 with_background=with_background, 477 gap_closing=gap_closing, 478 min_z_extent=min_z_extent, 479 verbose=verbose, 480 ) 481 if return_embeddings: 482 return segmentation, image_embeddings 483 else: 484 return segmentation
Automatically segment objects in a volume.
First segments slices individually in 2d and then merges them across 3d based on overlap of objects between slices.
Arguments:
- volume: The input volume.
- predictor: The Segment Anything predictor.
- segmentor: The instance segmentation class.
- embedding_path: The path to save pre-computed embeddings.
- with_background: Whether the segmentation has background. By default, set to 'True'.
- gap_closing: If given, gaps in the segmentation are closed with a binary closing operation. The value is used to determine the number of iterations for the closing.
- min_z_extent: Require a minimal extent in z for the segmented objects. This can help to prevent segmentation artifacts.
- tile_shape: Shape of the tiles for tiled prediction. By default prediction is run without tiling.
- halo: Overlap of the tiles for tiled prediction. By default prediction is run without tiling.
- verbose: Verbosity flag. By default, set to 'True'.
- return_embeddings: Whether to return the precomputed image embeddings. By default, set to 'False'.
- batch_size: The batch size to compute image embeddings over planes. By default, set to '1'.
- kwargs: Keyword arguments for the 'generate' method of the 'segmentor'.
Returns:
The segmentation.
652def track_across_frames( 653 timeseries: np.ndarray, 654 segmentation: np.ndarray, 655 gap_closing: Optional[int] = None, 656 min_time_extent: Optional[int] = None, 657 mode: str = "greedy", 658 tracking_model: str = "general_2d", 659 verbose: bool = True, 660 pbar_init: Optional[callable] = None, 661 pbar_update: Optional[callable] = None, 662 output_folder: Optional[Union[os.PathLike, str]] = None, 663) -> Tuple[np.ndarray, List[Dict]]: 664 """Track segmented objects over time. 665 666 This function uses Trackastra: https://www.ecva.net/papers/eccv_2024/papers_ECCV/papers/09819.pdf 667 for tracking. Please cite it if you use the automated tracking functionality. 668 669 Args: 670 timeseries: The input timeseries of images. 671 segmentation: The segmentation. Expect segmentation results per frame 672 that are relabeled so that segmentation ids don't overlap. 673 gap_closing: If given, gaps in the segmentation are closed with a binary closing 674 operation. The value is used to determine the number of iterations for the closing. 675 min_time_extent: Require a minimal extent in time for the tracked objects. 676 mode: The trackastra linking solver. One of 'greedy_nodiv', 'greedy' or 'ilp'. 677 'ilp' uses the motile solver. By default, set to 'greedy'. 678 tracking_model: The pretrained trackastra model to use. By default, set to 'general_2d'. 679 verbose: Verbosity flag. By default, set to 'True'. 680 pbar_init: Function to initialize the progress bar. 681 pbar_update: Function to update the progress bar. 682 output_folder: The folder where the tracking results are stored in CTC format. 683 684 Returns: 685 The tracking result. Each object is colored by its track id. 686 The lineages, which correspond to the cell divisions. Lineages are represented by a list of dicts, 687 with each dict encoding a lineage, where keys correspond to parent track ids. 688 Each key either maps to a list with two child track ids (cell division) or to an empty list (no division). 689 """ 690 _require_trackastra() 691 692 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init=pbar_init, pbar_update=pbar_update) 693 694 if gap_closing is not None and gap_closing > 0: 695 segmentation = _preprocess_closing(segmentation, gap_closing, pbar_update) 696 697 segmentation, lineage = _tracking_impl( 698 timeseries=np.asarray(timeseries), 699 segmentation=segmentation, 700 mode=mode, 701 min_time_extent=min_time_extent, 702 tracking_model=tracking_model, 703 output_folder=output_folder, 704 ) 705 return segmentation, lineage
Track segmented objects over time.
This function uses Trackastra: https://www.ecva.net/papers/eccv_2024/papers_ECCV/papers/09819.pdf for tracking. Please cite it if you use the automated tracking functionality.
Arguments:
- timeseries: The input timeseries of images.
- segmentation: The segmentation. Expect segmentation results per frame that are relabeled so that segmentation ids don't overlap.
- gap_closing: If given, gaps in the segmentation are closed with a binary closing operation. The value is used to determine the number of iterations for the closing.
- min_time_extent: Require a minimal extent in time for the tracked objects.
- mode: The trackastra linking solver. One of 'greedy_nodiv', 'greedy' or 'ilp'. 'ilp' uses the motile solver. By default, set to 'greedy'.
- tracking_model: The pretrained trackastra model to use. By default, set to 'general_2d'.
- verbose: Verbosity flag. By default, set to 'True'.
- pbar_init: Function to initialize the progress bar.
- pbar_update: Function to update the progress bar.
- output_folder: The folder where the tracking results are stored in CTC format.
Returns:
The tracking result. Each object is colored by its track id. The lineages, which correspond to the cell divisions. Lineages are represented by a list of dicts, with each dict encoding a lineage, where keys correspond to parent track ids. Each key either maps to a list with two child track ids (cell division) or to an empty list (no division).
708def automatic_tracking_implementation( 709 timeseries: np.ndarray, 710 predictor: SamPredictor, 711 segmentor: AutoSegBase, 712 embedding_path: Optional[Union[str, os.PathLike]] = None, 713 gap_closing: Optional[int] = None, 714 min_time_extent: Optional[int] = None, 715 mode: str = "greedy", 716 tracking_model: str = "general_2d", 717 tile_shape: Optional[Tuple[int, int]] = None, 718 halo: Optional[Tuple[int, int]] = None, 719 verbose: bool = True, 720 return_embeddings: bool = False, 721 batch_size: int = 1, 722 output_folder: Optional[Union[os.PathLike, str]] = None, 723 **kwargs, 724) -> Tuple[np.ndarray, List[Dict]]: 725 """Automatically track objects in a timesries based on per-frame automatic segmentation. 726 727 This function uses Trackastra: https://www.ecva.net/papers/eccv_2024/papers_ECCV/papers/09819.pdf 728 for tracking. Please cite it if you use the automated tracking functionality. 729 730 Args: 731 timeseries: The input timeseries of images. 732 predictor: The SAM model. 733 segmentor: The instance segmentation class. 734 embedding_path: The path to save pre-computed embeddings. 735 gap_closing: If given, gaps in the segmentation are closed with a binary closing 736 operation. The value is used to determine the number of iterations for the closing. 737 min_time_extent: Require a minimal extent in time for the tracked objects. 738 mode: The trackastra linking solver. One of 'greedy_nodiv', 'greedy' or 'ilp'. 739 'ilp' uses the motile solver. By default, set to 'greedy'. 740 tracking_model: The pretrained trackastra model to use. By default, set to 'general_2d'. 741 tile_shape: Shape of the tiles for tiled prediction. By default prediction is run without tiling. 742 halo: Overlap of the tiles for tiled prediction. By default prediction is run without tiling. 743 verbose: Verbosity flag. By default, set to 'True'. 744 return_embeddings: Whether to return the precomputed image embeddings. By default, set to 'False'. 745 batch_size: The batch size to compute image embeddings over planes. By default, set to '1'. 746 output_folder: The folder where the tracking results are stored in CTC format. 747 kwargs: Keyword arguments for the 'generate' method of the 'segmentor'. 748 749 Returns: 750 The tracking result. Each object is colored by its track id. 751 The lineages, which correspond to the cell divisions. Lineages are represented by a list of dicts, 752 with each dict encoding a lineage, where keys correspond to parent track ids. 753 Each key either maps to a list with two child track ids (cell division) or to an empty list (no division). 754 """ 755 _require_trackastra() 756 757 segmentation, image_embeddings = _segment_slices( 758 timeseries, predictor, segmentor, embedding_path, verbose, 759 tile_shape=tile_shape, halo=halo, batch_size=batch_size, 760 **kwargs, 761 ) 762 763 segmentation, lineage = track_across_frames( 764 timeseries=timeseries, 765 segmentation=segmentation, 766 gap_closing=gap_closing, 767 min_time_extent=min_time_extent, 768 mode=mode, 769 tracking_model=tracking_model, 770 verbose=verbose, 771 output_folder=output_folder, 772 ) 773 774 if return_embeddings: 775 return segmentation, lineage, image_embeddings 776 else: 777 return segmentation, lineage
Automatically track objects in a timesries based on per-frame automatic segmentation.
This function uses Trackastra: https://www.ecva.net/papers/eccv_2024/papers_ECCV/papers/09819.pdf for tracking. Please cite it if you use the automated tracking functionality.
Arguments:
- timeseries: The input timeseries of images.
- predictor: The SAM model.
- segmentor: The instance segmentation class.
- embedding_path: The path to save pre-computed embeddings.
- gap_closing: If given, gaps in the segmentation are closed with a binary closing operation. The value is used to determine the number of iterations for the closing.
- min_time_extent: Require a minimal extent in time for the tracked objects.
- mode: The trackastra linking solver. One of 'greedy_nodiv', 'greedy' or 'ilp'. 'ilp' uses the motile solver. By default, set to 'greedy'.
- tracking_model: The pretrained trackastra model to use. By default, set to 'general_2d'.
- tile_shape: Shape of the tiles for tiled prediction. By default prediction is run without tiling.
- halo: Overlap of the tiles for tiled prediction. By default prediction is run without tiling.
- verbose: Verbosity flag. By default, set to 'True'.
- return_embeddings: Whether to return the precomputed image embeddings. By default, set to 'False'.
- batch_size: The batch size to compute image embeddings over planes. By default, set to '1'.
- output_folder: The folder where the tracking results are stored in CTC format.
- kwargs: Keyword arguments for the 'generate' method of the 'segmentor'.
Returns:
The tracking result. Each object is colored by its track id. The lineages, which correspond to the cell divisions. Lineages are represented by a list of dicts, with each dict encoding a lineage, where keys correspond to parent track ids. Each key either maps to a list with two child track ids (cell division) or to an empty list (no division).
780def get_napari_track_data( 781 segmentation: np.ndarray, lineages: List[Dict], n_threads: Optional[int] = None 782) -> Tuple[np.ndarray, Dict[int, List]]: 783 """Derive the inputs for the napari tracking layer from a tracking result. 784 785 Args: 786 segmentation: The segmentation, after relabeling with track ids. 787 lineages: The lineage information. 788 n_threads: Number of threads for extracting the track data from the segmentation. 789 790 Returns: 791 The array with the track data expected by napari. 792 The parent dictionary for napari. 793 """ 794 if n_threads is None: 795 n_threads = mp.cpu_count() 796 797 def compute_props(t): 798 props = regionprops(segmentation[t]) 799 # Create the track data representation for napari, which expects: 800 # track_id, timepoint, y, x 801 track_data = np.array([[prop.label, t] + list(prop.centroid) for prop in props]) 802 return track_data 803 804 with futures.ThreadPoolExecutor(n_threads) as tp: 805 track_data = list(tp.map(compute_props, range(segmentation.shape[0]))) 806 track_data = [data for data in track_data if data.size > 0] 807 # The segmentation can be empty, e.g. if 'min_time_extent' filtered out all tracks. 808 track_data = np.concatenate(track_data) if track_data else np.zeros((0, 4), dtype="float64") 809 810 # The graph representation of napari uses the children as keys and the parents as values, 811 # whereas our representation uses parents as keys and children as values. 812 # Hence, we need to translate the representation. 813 parent_graph = { 814 child: [parent] for lineage in lineages for parent, children in lineage.items() for child in children 815 } 816 817 return track_data, parent_graph
Derive the inputs for the napari tracking layer from a tracking result.
Arguments:
- segmentation: The segmentation, after relabeling with track ids.
- lineages: The lineage information.
- n_threads: Number of threads for extracting the track data from the segmentation.
Returns:
The array with the track data expected by napari. The parent dictionary for napari.
820def export_tracking_result_to_ctc( 821 segmentation: np.ndarray, 822 lineages: List[Dict], 823 output_folder: Union[os.PathLike, str], 824) -> None: 825 """Export a tracking result to the Cell Tracking Challenge (CTC) format. 826 827 This writes the standard CTC folder layout into 'output_folder': 828 - 'TRA/man_track.txt', the lineage file with one space-separated row 'L B E P' per track 829 (track id, first frame, last frame, parent track id, where the parent is 0 if the track has no parent). 830 - 'TRA/man_track<frame>.tif', the per-frame tracking masks, with each object labeled by its track id. 831 - 'SEG/man_seg<frame>.tif', the per-frame segmentation masks. 832 833 Args: 834 segmentation: The tracking result of shape (T, Y, X), with each object labeled by its track id. 835 lineages: The lineage information, a list of dicts mapping each parent track id to its child track ids. 836 output_folder: The folder where the CTC results are written, with 'TRA' and 'SEG' subfolders. 837 """ 838 if segmentation.ndim != 3: 839 raise ValueError(f"Expected a 3d (T, Y, X) tracking result, got shape {segmentation.shape}.") 840 841 tra_folder = os.path.join(output_folder, "TRA") 842 seg_folder = os.path.join(output_folder, "SEG") 843 os.makedirs(tra_folder, exist_ok=True) 844 os.makedirs(seg_folder, exist_ok=True) 845 846 # Map each child track to its parent track. Tracks without a parent get 0, as expected by the CTC format. 847 child_to_parent = {} 848 for lineage in lineages: 849 for parent, children in lineage.items(): 850 for child in children: 851 child_to_parent[child] = parent 852 853 # Determine the first and last frame in which each track id is present. 854 n_frames = segmentation.shape[0] 855 first_frame, last_frame = {}, {} 856 for t in range(n_frames): 857 for label_id in np.unique(segmentation[t]): 858 label_id = int(label_id) 859 if label_id == 0: 860 continue 861 if label_id not in first_frame: 862 first_frame[label_id] = t 863 last_frame[label_id] = t 864 865 # Write the lineage file into the tracking folder. 866 with open(os.path.join(tra_folder, "man_track.txt"), "w") as f: 867 for label_id in sorted(first_frame.keys()): 868 parent = child_to_parent.get(label_id, 0) 869 f.write(f"{label_id} {first_frame[label_id]} {last_frame[label_id]} {parent}\n") 870 871 # Write the per-frame masks, using uint16 if the track ids fit and uint32 otherwise. 872 # The tracking masks (TRA) and segmentation masks (SEG) share the same track-id labeling. 873 max_id = int(segmentation.max()) 874 dtype = "uint16" if max_id < np.iinfo("uint16").max else "uint32" 875 n_digits = max(4, len(str(n_frames - 1))) 876 for t in range(n_frames): 877 frame = segmentation[t].astype(dtype) 878 imageio.imwrite(os.path.join(tra_folder, f"man_track{t:0{n_digits}d}.tif"), frame) 879 imageio.imwrite(os.path.join(seg_folder, f"man_seg{t:0{n_digits}d}.tif"), frame)
Export a tracking result to the Cell Tracking Challenge (CTC) format.
This writes the standard CTC folder layout into 'output_folder':
- 'TRA/man_track.txt', the lineage file with one space-separated row 'L B E P' per track (track id, first frame, last frame, parent track id, where the parent is 0 if the track has no parent).
- 'TRA/man_track.tif', the per-frame tracking masks, with each object labeled by its track id.
- 'SEG/man_seg.tif', the per-frame segmentation masks.
Arguments:
- segmentation: The tracking result of shape (T, Y, X), with each object labeled by its track id.
- lineages: The lineage information, a list of dicts mapping each parent track id to its child track ids.
- output_folder: The folder where the CTC results are written, with 'TRA' and 'SEG' subfolders.
982def export_tracking_result_to_geff( 983 segmentation: np.ndarray, 984 lineages: List[Dict], 985 output_path: Union[os.PathLike, str], 986) -> Path: 987 """Export a tracking result to GEFF. 988 989 The export follows the Trackastra GEFF layout: a zarr group containing the tracking masks in 990 'segmentation' and the graph in 'tracking_graph.geff'. 991 992 Args: 993 segmentation: The tracking result of shape (T, Y, X), with each object labeled by its track id. 994 lineages: The lineage information, a list of dicts mapping each parent track id to its child track ids. 995 output_path: The zarr path to write to. If a directory is passed, 'tracking_result.zarr' is written in it. 996 997 Returns: 998 The path of the written zarr group. 999 """ 1000 try: 1001 from trackastra.tracking import write_to_geff 1002 except ImportError as e: 1003 raise RuntimeError( 1004 "GEFF export requires trackastra with GEFF support. Install a recent trackastra/geff version." 1005 ) from e 1006 1007 output_path = _normalize_output_path(output_path, "tracking_result.zarr", ".zarr") 1008 graph, _, _ = _tracking_result_to_graph(segmentation, lineages) 1009 write_to_geff(graph, segmentation, output_path) 1010 return output_path
Export a tracking result to GEFF.
The export follows the Trackastra GEFF layout: a zarr group containing the tracking masks in 'segmentation' and the graph in 'tracking_graph.geff'.
Arguments:
- segmentation: The tracking result of shape (T, Y, X), with each object labeled by its track id.
- lineages: The lineage information, a list of dicts mapping each parent track id to its child track ids.
- output_path: The zarr path to write to. If a directory is passed, 'tracking_result.zarr' is written in it.
Returns:
The path of the written zarr group.
1220def export_tracking_result_to_trackmate_xml( 1221 segmentation: np.ndarray, 1222 lineages: List[Dict], 1223 output_path: Union[os.PathLike, str], 1224) -> Path: 1225 """Export a tracking result to TrackMate XML. 1226 1227 The XML contains all per-frame detections as TrackMate spots and the committed tracking graph as TrackMate tracks. 1228 1229 Args: 1230 segmentation: The tracking result of shape (T, Y, X), with each object labeled by its track id. 1231 lineages: The lineage information, a list of dicts mapping each parent track id to its child track ids. 1232 output_path: The XML path to write to. If a directory is passed, 'tracking_result.xml' is written in it. 1233 1234 Returns: 1235 The path of the written XML file. 1236 """ 1237 output_path = _normalize_output_path(output_path, "tracking_result.xml", ".xml") 1238 graph, records, records_by_node = _tracking_result_to_graph(segmentation, lineages) 1239 1240 root = ET.Element("TrackMate", {"version": "micro-sam"}) 1241 ET.SubElement(root, "Log").text = "Created by micro-sam." 1242 model = ET.SubElement(root, "Model", {"spatialunits": "pixel", "timeunits": "frame"}) 1243 _add_trackmate_feature_declarations(model) 1244 _add_trackmate_spots(model, records) 1245 _add_trackmate_tracks(model, graph, records_by_node) 1246 _add_trackmate_settings(root, segmentation) 1247 ET.SubElement(root, "GUIState", {"state": "ConfigureViews"}) 1248 ET.SubElement(root, "DisplaySettings") 1249 1250 tree = ET.ElementTree(root) 1251 ET.indent(tree, space=" ") 1252 tree.write(output_path, encoding="UTF-8", xml_declaration=True) 1253 return output_path
Export a tracking result to TrackMate XML.
The XML contains all per-frame detections as TrackMate spots and the committed tracking graph as TrackMate tracks.
Arguments:
- segmentation: The tracking result of shape (T, Y, X), with each object labeled by its track id.
- lineages: The lineage information, a list of dicts mapping each parent track id to its child track ids.
- output_path: The XML path to write to. If a directory is passed, 'tracking_result.xml' is written in it.
Returns:
The path of the written XML file.