micro_sam.v1.automatic_segmentation

  1import os
  2import warnings
  3from glob import glob
  4from pathlib import Path
  5from functools import partial
  6from typing import Dict, List, Optional, Union, Tuple, Literal
  7
  8import numpy as np
  9from tqdm import tqdm
 10import imageio.v3 as imageio
 11
 12from torch_em.data.datasets.util import split_kwargs
 13
 14from .. import util
 15from ..util import AutoSegBase
 16from .util import get_sam_model, precompute_image_embeddings, get_model_names
 17from .multi_dimensional_segmentation import automatic_3d_segmentation, automatic_tracking_implementation
 18from .instance_segmentation import (
 19    get_instance_segmentation_generator, get_decoder,
 20    AutomaticMaskGenerator, TiledAutomaticMaskGenerator,
 21    AutomaticPromptGenerator, TiledAutomaticPromptGenerator,
 22    InstanceSegmentationWithDecoder, TiledInstanceSegmentationWithDecoder,
 23    DEFAULT_SEGMENTATION_MODE_WITH_DECODER,
 24)
 25
 26
 27def get_predictor_and_segmenter(
 28    model_type: str,
 29    checkpoint: Optional[Union[os.PathLike, str]] = None,
 30    device: str = None,
 31    segmentation_mode: Optional[Literal["amg", "ais", "apg"]] = None,
 32    is_tiled: bool = False,
 33    predictor=None,
 34    state=None,
 35    **kwargs,
 36) -> Tuple[util.SamPredictor, AutoSegBase]:
 37    f"""Get the Segment Anything model and class for automatic instance segmentation.
 38
 39    Args:
 40        model_type: The Segment Anything model choice.
 41        checkpoint: The filepath to the stored model checkpoints.
 42        device: The torch device. By default, automatically chooses the best available device.
 43        segmentation_mode: The segmentation mode. One of 'amg', 'ais', or 'apg'.
 44            By default, '{DEFAULT_SEGMENTATION_MODE_WITH_DECODER}' is used
 45            if a decoder is passed, otherwise 'amg' is used.
 46        is_tiled: Whether to return segmenter for performing segmentation in tiling window style.
 47            By default, set to 'False'.
 48        predictor: The pre-loaded predictor (optional).
 49        state: The pre-loaded state (optional).
 50        kwargs: Keyword arguments for the automatic mask generation class.
 51
 52    Returns:
 53        The Segment Anything model.
 54        The automatic instance segmentation class.
 55    """
 56    # Get the predictor and state for Segment Anything Model.
 57    if predictor is None:
 58        device = util.get_device(device=device)
 59        predictor, state = get_sam_model(
 60            model_type=model_type, device=device, checkpoint_path=checkpoint, return_state=True
 61        )
 62    else:
 63        assert state is not None
 64
 65    if segmentation_mode in (None, "auto"):
 66        segmentation_mode = DEFAULT_SEGMENTATION_MODE_WITH_DECODER if "decoder_state" in state else "amg"
 67
 68    if segmentation_mode.lower() == "amg":
 69        decoder = None
 70    else:
 71        if "decoder_state" not in state:
 72            raise RuntimeError(
 73                f"You have passed 'segmentation_mode={segmentation_mode}', but your model does not contain a decoder."
 74            )
 75        decoder_state = state["decoder_state"]
 76        decoder = get_decoder(image_encoder=predictor.model.image_encoder, decoder_state=decoder_state, device=device)
 77
 78    segmenter = get_instance_segmentation_generator(
 79        predictor=predictor, is_tiled=is_tiled, decoder=decoder, segmentation_mode=segmentation_mode, **kwargs
 80    )
 81    return predictor, segmenter
 82
 83
 84def _add_suffix_to_output_path(output_path: Union[str, os.PathLike], suffix: str) -> str:
 85    fpath = Path(output_path).resolve()
 86    fext = fpath.suffix if fpath.suffix else ".tif"
 87    return str(fpath.with_name(f"{fpath.stem}{suffix}{fext}"))
 88
 89
 90def automatic_tracking(
 91    predictor: util.SamPredictor,
 92    segmenter: AutoSegBase,
 93    input_path: Union[Union[os.PathLike, str], np.ndarray],
 94    output_path: Optional[Union[os.PathLike, str]] = None,
 95    embedding_path: Optional[Union[os.PathLike, str]] = None,
 96    key: Optional[str] = None,
 97    tile_shape: Optional[Tuple[int, int]] = None,
 98    halo: Optional[Tuple[int, int]] = None,
 99    verbose: bool = True,
100    return_embeddings: bool = False,
101    annotate: bool = False,
102    batch_size: int = 1,
103    mode: str = "greedy",
104    tracking_model: str = "general_2d",
105    **generate_kwargs
106) -> Tuple[np.ndarray, List[Dict]]:
107    """Run automatic tracking for the input timeseries.
108
109    Args:
110        predictor: The Segment Anything model.
111        segmenter: The automatic instance segmentation class.
112        input_path: input_path: The input image file(s). Can either be a single image file (e.g. tif or png),
113            or a container file (e.g. hdf5 or zarr).
114        output_path: The folder where the tracking outputs will be saved in CTC format.
115        embedding_path: The path where the embeddings are cached already / will be saved.
116        key: The key to the input file. This is needed for container files (eg. hdf5 or zarr)
117            or to load several images as 3d volume. Provide a glob patterm, eg. "*.tif", for this case.
118        tile_shape: Shape of the tiles for tiled prediction. By default prediction is run without tiling.
119        halo: Overlap of the tiles for tiled prediction. By default prediction is run without tiling.
120        verbose: Verbosity flag. By default, set to 'True'.
121        return_embeddings: Whether to return the precomputed image embeddings.
122            By default, does not return the embeddings.
123        annotate: Whether to activate the annotator for continue annotation process.
124            By default, does not activate the annotator.
125        batch_size: The batch size to compute image embeddings over tiles / z-planes.
126            By default, does it sequentially, i.e. one after the other.
127        mode: The trackastra linking solver. One of 'greedy_nodiv', 'greedy' or 'ilp'.
128            'ilp' uses the motile solver. By default, set to 'greedy'.
129        tracking_model: The pretrained trackastra model to use. By default, set to 'general_2d'.
130        generate_kwargs: optional keyword arguments for the generate function of the AMG, APG, or AIS class.
131
132    Returns:
133        The tracking result as a timeseries, where each object is labeled by its track id.
134        The lineages representing cell divisions, stored as a dictionary.
135    """
136    # Load the input image file.
137    # We assume that it has to be read from file if it is a str or pathlike.
138    # Otherwise we assume it is a numpy array like object.
139    image_data = util.load_image_data(input_path, key) if isinstance(input_path, (str, os.PathLike)) else input_path
140
141    if (image_data.ndim != 3) and (image_data.ndim != 4 and image_data.shape[-1] != 3):
142        raise ValueError(f"The inputs does not match the shape expectation of 3d inputs: {image_data.shape}")
143
144    gap_closing, min_time_extent = generate_kwargs.get("gap_closing"), generate_kwargs.get("min_time_extent")
145    segmentation, lineage, image_embeddings = automatic_tracking_implementation(
146        image_data,
147        predictor,
148        segmenter,
149        embedding_path=embedding_path,
150        gap_closing=gap_closing,
151        min_time_extent=min_time_extent,
152        tile_shape=tile_shape,
153        halo=halo,
154        verbose=verbose,
155        batch_size=batch_size,
156        mode=mode,
157        tracking_model=tracking_model,
158        return_embeddings=True,
159        output_folder=output_path,
160        **generate_kwargs,
161    )
162
163    if annotate:
164        # TODO We need to support initialization of the tracking annotator with the tracking result for this.
165        raise NotImplementedError("Annotation after running the automated tracking is currently not supported.")
166
167    if return_embeddings:
168        return segmentation, lineage, image_embeddings
169    else:
170        return segmentation, lineage
171
172
173def automatic_instance_segmentation(
174    predictor: util.SamPredictor,
175    segmenter: AutoSegBase,
176    input_path: Union[Union[os.PathLike, str], np.ndarray],
177    output_path: Optional[Union[os.PathLike, str]] = None,
178    embedding_path: Optional[Union[os.PathLike, str]] = None,
179    mask_path: Optional[Union[Union[os.PathLike, str], np.ndarray]] = None,
180    key: Optional[str] = None,
181    mask_key: Optional[str] = None,
182    ndim: Optional[int] = None,
183    tile_shape: Optional[Tuple[int, int]] = None,
184    halo: Optional[Tuple[int, int]] = None,
185    verbose: bool = True,
186    return_embeddings: bool = False,
187    annotate: bool = False,
188    batch_size: int = 1,
189    **generate_kwargs
190) -> np.ndarray:
191    """Run automatic segmentation for the input image.
192
193    Args:
194        predictor: The Segment Anything model.
195        segmenter: The automatic instance segmentation class.
196        input_path: input_path: The input image file(s). Can either be a single image file (e.g. tif or png),
197            or a container file (e.g. hdf5 or zarr).
198        output_path: The output path where the instance segmentations will be saved.
199        embedding_path: The path where the embeddings are cached already / will be saved.
200        mask_path: The path to an optional foreground mask. Areas outside of the foreground will not be processed.
201        key: The key to the input file. This is needed for container files (eg. hdf5 or zarr)
202            or to load several images as 3d volume. Provide a glob patterm, eg. "*.tif", for this case.
203        mask_key: The key to the (optional) foreground mask.
204        ndim: The dimensionality of the data. By default the dimensionality of the data will be used.
205            If you have RGB data you have to specify this explicitly, e.g. pass ndim=2 for 2d segmentation of RGB.
206        tile_shape: Shape of the tiles for tiled prediction. By default prediction is run without tiling.
207        halo: Overlap of the tiles for tiled prediction. By default prediction is run without tiling.
208        verbose: Verbosity flag. By default, set to 'True'.
209        return_embeddings: Whether to return the precomputed image embeddings.
210            By default, does not return the embeddings.
211        annotate: Whether to activate the annotator for continue annotation process.
212            By default, does not activate the annotator.
213        batch_size: The batch size to compute image embeddings over tiles / z-planes.
214            By default, does it sequentially, i.e. one after the other.
215        generate_kwargs: optional keyword arguments for the generate function of the AMG or AIS class.
216
217    Returns:
218        The segmentation result.
219    """
220    # Avoid overwriting already stored segmentations.
221    if output_path is not None:
222        output_path = Path(output_path).with_suffix(".tif")
223        if os.path.exists(output_path):
224            print(f"The segmentation results are already stored at '{os.path.abspath(output_path)}'.")
225            return
226
227    # We assume that it has to be read from file if it is a str or pathlike.
228    # Otherwise we assume it is a numpy array like object.
229    image_data = util.load_image_data(input_path, key) if isinstance(input_path, (str, os.PathLike)) else input_path
230
231    ndim = image_data.ndim if ndim is None else ndim
232
233    # Load the mask defining foreground if it was given.
234    if mask_path is None:
235        mask = None
236    else:
237        mask = util.load_image_data(mask_path, mask_key) if isinstance(mask_path, (str, os.PathLike)) else mask_path
238
239    if ndim == 2:
240        if (image_data.ndim != 2) and (image_data.ndim != 3 and image_data.shape[-1] != 3):
241            raise ValueError(f"The inputs does not match the shape expectation of 2d inputs: {image_data.shape}")
242
243        # Precompute the image embeddings.
244        image_embeddings = precompute_image_embeddings(
245            predictor=predictor,
246            input_=image_data,
247            save_path=embedding_path,
248            ndim=ndim,
249            tile_shape=tile_shape,
250            halo=halo,
251            verbose=verbose,
252            batch_size=batch_size,
253            mask=mask,
254        )
255        initialize_kwargs = dict(image=image_data, image_embeddings=image_embeddings, verbose=verbose)
256        if mask is not None:
257            initialize_kwargs["mask"] = mask
258
259        # If we run AIS with tiling then we use the same tile shape for the watershed postprocessing.
260        # In this case, we also add the batch size to the initialize kwargs,
261        # so that the segmentation decoder can be applied in a batched fashion.
262        if isinstance(segmenter, InstanceSegmentationWithDecoder) and tile_shape is not None:
263            if not isinstance(segmenter, TiledAutomaticPromptGenerator):
264                generate_kwargs.update({"tile_shape": tile_shape, "halo": halo})
265            initialize_kwargs["batch_size"] = batch_size
266
267        segmenter.initialize(**initialize_kwargs)
268        instances = segmenter.generate(**generate_kwargs)
269
270    else:
271        if (image_data.ndim != 3) and (image_data.ndim != 4 and image_data.shape[-1] != 3):
272            raise ValueError(f"The inputs does not match the shape expectation of 3d inputs: {image_data.shape}")
273        if mask is not None:
274            raise NotImplementedError
275
276        instances, image_embeddings = automatic_3d_segmentation(
277            volume=image_data,
278            predictor=predictor,
279            segmentor=segmenter,
280            embedding_path=embedding_path,
281            tile_shape=tile_shape,
282            halo=halo,
283            verbose=verbose,
284            return_embeddings=True,
285            batch_size=batch_size,
286            **generate_kwargs
287        )
288
289    # Before starting to annotate, if at all desired, store the automatic segmentations in the first stage.
290    if output_path is not None:
291        _output_path = _add_suffix_to_output_path(output_path, "_automatic") if annotate else output_path
292        imageio.imwrite(_output_path, instances, compression="zlib")
293        if verbose:
294            print(f"The automatic segmentation results are stored at '{os.path.abspath(_output_path)}'.")
295
296    # Allow opening the automatic segmentation in the annotator for further annotation, if desired.
297    if annotate:
298        from micro_sam.sam_annotator import annotator
299
300        viewer = annotator(
301            image=image_data,
302            ndim=ndim,
303            model_type=predictor.model_name,
304            embedding_path=image_embeddings,  # Providing the precomputed image embeddings.
305            segmentation_result=instances,  # Initializes the automatic segmentation to the annotator.
306            tile_shape=tile_shape,
307            halo=halo,
308            return_viewer=True,  # Returns the viewer, which allows the user to store the updated segmentations.
309        )
310
311        # Start the GUI here
312        import napari
313        napari.run()
314
315        # We extract the segmentation in "committed_objects" layer, where the user either:
316        # a) Performed interactive segmentation / corrections and committed them, OR
317        # b) Did not do anything and closed the annotator, i.e. keeps the segmentations as it is.
318        instances = viewer.layers["committed_objects"].data
319
320        # Save the instance segmentation, if 'output_path' provided.
321        if output_path is not None:
322            imageio.imwrite(output_path, instances, compression="zlib")
323            if verbose:
324                print(f"The final segmentation results are stored at '{os.path.abspath(output_path)}'.")
325
326    if return_embeddings:
327        return instances, image_embeddings
328    else:
329        return instances
330
331
332def _get_inputs_from_paths(paths, pattern):
333    "Function to get all filepaths in a directory."
334
335    if isinstance(paths, str):
336        paths = [paths]
337
338    fpaths = []
339    for path in paths:
340        if os.path.isfile(path):  # It is just one filepath.
341            fpaths.append(path)
342        else:  # A directory: match files with the pattern, defaulting to all files if none is given.
343            hits = glob(os.path.join(path, pattern if pattern is not None else "*"))
344            fpaths.extend(p for p in hits if os.path.isfile(p))
345
346    return fpaths
347
348
349def main(argv=None):
350    """@private"""
351    import argparse
352
353    available_models = list(get_model_names())
354    available_models = ", ".join(available_models)
355
356    parser = argparse.ArgumentParser(
357        description="Run automatic segmentation or tracking for 2d, 3d or timeseries data.\n"
358        "Either a single input file or multiple input files are supported. You can specify multiple files "
359        "by either providing multiple filepaths to the '--i/--input_paths' argument, or by providing an argument "
360        "to '--pattern' to use a wildcard pattern ('*') for selecting multiple files.\n"
361        "NOTE: for automatic 3d segmentation or tracking the data has to be stored as volume / timeseries, "
362        "stacking individual tif images is not supported.\n"
363        "Segmentation is performed using one of the three modes supported by micro_sam: \n"
364        "automatic instance segmentation (AIS), automatic prompt generation (APG) or automatic mask generation (AMG).\n"
365        "In addition to the options listed below, "
366        "you can also passed additional arguments for these three segmentation modes:\n"
367        "For AIS: '--center_distance_threshold', '--boundary_distance_threshold' and other arguments of `InstanceSegmentationWithDecoder.generate`.\n"  # noqa
368        "FOR APG: '--center_distance_threshold', '--boundary_distance_threshold' and other arguments of `AutomaticPromptGenerator.generate`.\n"  # noqa
369        "For AMG: '--pred_iou_thresh', '--stability_score_thresh' and other arguments of `AutomaticMaskGenerator.generate`."  # noqa
370    )
371    parser.add_argument(
372        "-i", "--input_path", required=True, type=str, nargs="+",
373        help="The filepath(s) to the image data. Supports all data types that can be read by imageio (e.g. tif, png, ...) "  # noqa
374        "or elf.io.open_file (e.g. hdf5, zarr, mrc). For the latter you also need to pass the 'key' parameter."
375    )
376    parser.add_argument(
377        "-o", "--output_path", required=True, type=str,
378        help="The filepath to store the results. If multiple inputs are provied, "
379        "this should be a folder. For a single image, you should provide the path to a tif file for the output segmentation."  # noqa
380        "NOTE: Segmentation results are stored as tif files, tracking results in the CTC fil format ."
381    )
382    parser.add_argument(
383        "-e", "--embedding_path", default=None, type=str,
384        help="An optional path where the embeddings will be saved. If multiple inputs are provided, "
385        "this should be a folder. Otherwise you can store embeddings in single zarr file."
386    )
387    parser.add_argument(
388        "--pattern", type=str, help="Pattern / wildcard for selecting files in a folder. To select all files use '*'."
389    )
390    parser.add_argument(
391        "-k", "--key", default=None, type=str,
392        help="The key for opening data with elf.io.open_file. This is the internal path for a hdf5 or zarr container, "
393        "for an image stack it is a wild-card, e.g. '*.png' and for mrc it is 'data'."
394    )
395    parser.add_argument(
396        "-m", "--model_type", default=util.DEFAULT_SAM1_MODEL, type=str,
397        help=f"The segment anything model that will be used, one of {available_models}."
398    )
399    parser.add_argument(
400        "-c", "--checkpoint", default=None, type=str, help="Checkpoint from which the SAM model will be loaded."
401    )
402    parser.add_argument(
403        "--tile_shape", nargs="+", type=int,
404        help="The tile shape for using tiled prediction. Example: --tile_shape 384 384.", default=None
405    )
406    parser.add_argument(
407        "--halo", nargs="+", type=int,
408        help="The halo for using tiled prediction. Example: --tile_shape 64 64.", default=None
409    )
410    parser.add_argument(
411        "-n", "--ndim", default=None, type=int,
412        help="The number of spatial dimensions in the data. Please specify this if your data has a channel dimension."
413    )
414    parser.add_argument(
415        "--mode", default="auto", type=str,
416        help="The choice of automatic segmentation mode. Either 'auto', 'amg', 'apg', or 'ais'."
417    )
418    parser.add_argument(
419        "--annotate", action="store_true",
420        help="Whether to continue annotation after the automatic segmentation is generated."
421    )
422    parser.add_argument(
423        "-d", "--device", default=None, type=str,
424        help="The device to use for the predictor. Can be one of 'cuda', 'cpu' or 'mps' (only MAC)."
425        "By default the most performant available device will be selected."
426    )
427    parser.add_argument(
428        "--batch_size", type=int, default=1,
429        help="The batch size for computing image embeddings over tiles or z-plane. "
430        "By default, computes the image embeddings for one tile / z-plane at a time."
431    )
432    parser.add_argument(
433        "--tracking", action="store_true", help="Run automatic tracking instead of instance segmentation. "
434        "NOTE: It is only supported for timeseries inputs."
435    )
436    parser.add_argument("-v", "--verbose", action="store_true", help="Whether to allow verbosity of outputs.")
437
438    args, parameter_args = parser.parse_known_args(argv)
439
440    def _convert_argval(value):
441        # The values for the parsed arguments need to be in the expected input structure as provided.
442        # i.e. integers and floats should be in their original types.
443        try:
444            return int(value)
445        except ValueError:
446            return float(value)
447
448    # NOTE: the script below allows the possibility to catch additional parsed arguments which correspond to
449    # the automatic segmentation post-processing parameters (eg. 'center_distance_threshold' in AIS)
450    extra_kwargs = {
451        parameter_args[i].lstrip("--"): _convert_argval(parameter_args[i + 1]) for i in range(0, len(parameter_args), 2)
452    }
453
454    # Separate extra arguments as per where they should be passed in the automatic segmentation class.
455    # This is done to ensure the extra arguments are allocated to the desired location.
456    # eg. for AMG, 'points_per_side' is expected by '__init__',
457    # and 'stability_score_thresh' is expected in 'generate' method.
458    mode = args.mode
459    if mode in ("auto", None):
460        # We have to load the state to see if we have a decoder in this case.
461        device = util.get_device(device=args.device)
462        predictor, state = get_sam_model(
463            model_type=args.model_type, device=device, checkpoint_path=args.checkpoint, return_state=True
464        )
465        mode = DEFAULT_SEGMENTATION_MODE_WITH_DECODER if "decoder_state" in state else "amg"
466    else:
467        predictor, state = None, None
468
469    if mode.lower() == "amg":
470        segmenter_class = AutomaticMaskGenerator if args.tile_shape is None else TiledAutomaticMaskGenerator
471    elif mode.lower() == "ais":
472        segmenter_class = InstanceSegmentationWithDecoder if args.tile_shape is None else\
473            TiledInstanceSegmentationWithDecoder
474    elif mode.lower() == "apg":
475        segmenter_class = AutomaticPromptGenerator if args.tile_shape is None else TiledAutomaticPromptGenerator
476    else:
477        raise ValueError(f"Invalid segmentation_mode: {mode}. Choose one of 'amg', 'ais', or 'apg'.")
478    init_kwargs, generate_kwargs = split_kwargs(segmenter_class, **extra_kwargs)
479
480    predictor, segmenter = get_predictor_and_segmenter(
481        model_type=args.model_type,
482        checkpoint=args.checkpoint,
483        device=args.device,
484        segmentation_mode=mode,
485        is_tiled=args.tile_shape is not None,
486        predictor=predictor,
487        state=state,
488        **init_kwargs,
489    )
490
491    # Get the filepaths to input images (and other paths to store stuff, eg. segmentations and embeddings)
492    # Check whether the inputs are as expected, otherwise assort them.
493    input_paths = _get_inputs_from_paths(args.input_path, args.pattern)
494    assert len(input_paths) > 0, "'micro-sam' could not extract any image data internally."
495
496    output_path = args.output_path
497    embedding_path = args.embedding_path
498    has_one_input = len(input_paths) == 1
499
500    instance_seg_function = automatic_tracking if args.tracking else partial(
501        automatic_instance_segmentation, ndim=args.ndim
502    )
503
504    # Run automatic segmentation per image.
505    for input_path in tqdm(input_paths, desc="Run automatic " + ("tracking" if args.tracking else "segmentation")):
506        if has_one_input:  # When we have only one image / volume.
507            _embedding_fpath = embedding_path  # Either folder or zarr file, would work for both.
508
509            output_fdir = os.path.splitext(output_path)[0]
510            os.makedirs(output_fdir, exist_ok=True)
511
512            # For tracking, we ensure that the output path is a folder,
513            # i.e. does not have an extension. We throw a warning if the user provided an extension.
514            if args.tracking:
515                if os.path.splitext(output_path)[-1]:
516                    warnings.warn(
517                        f"The output folder has an extension '{os.path.splitext(output_path)[-1]}'. "
518                        "We remove it and treat it as a folder to store tracking outputs in CTC format."
519                    )
520                _output_fpath = output_fdir
521            else:  # Otherwise, we can store outputs for user directly in the provided filepath, ensuring extension .tif
522                _output_fpath = f"{output_fdir}.tif"
523
524        else:  # When we have multiple images.
525            # Get the input filename, without the extension.
526            input_name = str(Path(input_path).stem)
527
528            # Let's check the 'embedding_path'.
529            if embedding_path is None:  # For computing embeddings on-the-fly, we don't care about the path logic.
530                _embedding_fpath = embedding_path
531            else:  # Otherwise, store each embeddings inside a folder.
532                embedding_folder = os.path.splitext(embedding_path)[0]  # Treat the provided embedding path as folder.
533                os.makedirs(embedding_folder, exist_ok=True)
534                _embedding_fpath = os.path.join(embedding_folder, f"{input_name}.zarr")  # Create each embedding file.
535
536            # Get the output folder name.
537            output_folder = os.path.splitext(output_path)[0]
538            os.makedirs(output_folder, exist_ok=True)
539
540            # Next, let's check for output file to store segmentation (or tracks).
541            if args.tracking:  # For tracking, we store CTC outputs in subfolders, with input_name as folder.
542                _output_fpath = os.path.join(output_folder, input_name)
543            else:  # Otherwise, store each result inside a folder.
544                _output_fpath = os.path.join(output_folder, f"{input_name}.tif")
545
546        instance_seg_function(
547            predictor=predictor,
548            segmenter=segmenter,
549            input_path=input_path,
550            output_path=_output_fpath,
551            embedding_path=_embedding_fpath,
552            key=args.key,
553            tile_shape=args.tile_shape,
554            halo=args.halo,
555            annotate=args.annotate,
556            verbose=args.verbose,
557            batch_size=args.batch_size,
558            **generate_kwargs,
559        )
def get_predictor_and_segmenter( model_type: str, checkpoint: Union[str, os.PathLike, NoneType] = None, device: str = None, segmentation_mode: Optional[Literal['amg', 'ais', 'apg']] = None, is_tiled: bool = False, predictor=None, state=None, **kwargs) -> Tuple[mobile_sam.predictor.SamPredictor, micro_sam.util.AutoSegBase]:
28def get_predictor_and_segmenter(
29    model_type: str,
30    checkpoint: Optional[Union[os.PathLike, str]] = None,
31    device: str = None,
32    segmentation_mode: Optional[Literal["amg", "ais", "apg"]] = None,
33    is_tiled: bool = False,
34    predictor=None,
35    state=None,
36    **kwargs,
37) -> Tuple[util.SamPredictor, AutoSegBase]:
38    f"""Get the Segment Anything model and class for automatic instance segmentation.
39
40    Args:
41        model_type: The Segment Anything model choice.
42        checkpoint: The filepath to the stored model checkpoints.
43        device: The torch device. By default, automatically chooses the best available device.
44        segmentation_mode: The segmentation mode. One of 'amg', 'ais', or 'apg'.
45            By default, '{DEFAULT_SEGMENTATION_MODE_WITH_DECODER}' is used
46            if a decoder is passed, otherwise 'amg' is used.
47        is_tiled: Whether to return segmenter for performing segmentation in tiling window style.
48            By default, set to 'False'.
49        predictor: The pre-loaded predictor (optional).
50        state: The pre-loaded state (optional).
51        kwargs: Keyword arguments for the automatic mask generation class.
52
53    Returns:
54        The Segment Anything model.
55        The automatic instance segmentation class.
56    """
57    # Get the predictor and state for Segment Anything Model.
58    if predictor is None:
59        device = util.get_device(device=device)
60        predictor, state = get_sam_model(
61            model_type=model_type, device=device, checkpoint_path=checkpoint, return_state=True
62        )
63    else:
64        assert state is not None
65
66    if segmentation_mode in (None, "auto"):
67        segmentation_mode = DEFAULT_SEGMENTATION_MODE_WITH_DECODER if "decoder_state" in state else "amg"
68
69    if segmentation_mode.lower() == "amg":
70        decoder = None
71    else:
72        if "decoder_state" not in state:
73            raise RuntimeError(
74                f"You have passed 'segmentation_mode={segmentation_mode}', but your model does not contain a decoder."
75            )
76        decoder_state = state["decoder_state"]
77        decoder = get_decoder(image_encoder=predictor.model.image_encoder, decoder_state=decoder_state, device=device)
78
79    segmenter = get_instance_segmentation_generator(
80        predictor=predictor, is_tiled=is_tiled, decoder=decoder, segmentation_mode=segmentation_mode, **kwargs
81    )
82    return predictor, segmenter
def automatic_tracking( predictor: mobile_sam.predictor.SamPredictor, segmenter: micro_sam.util.AutoSegBase, input_path: Union[os.PathLike, str, numpy.ndarray], output_path: Union[str, os.PathLike, NoneType] = None, embedding_path: Union[str, os.PathLike, NoneType] = None, key: Optional[str] = None, tile_shape: Optional[Tuple[int, int]] = None, halo: Optional[Tuple[int, int]] = None, verbose: bool = True, return_embeddings: bool = False, annotate: bool = False, batch_size: int = 1, mode: str = 'greedy', tracking_model: str = 'general_2d', **generate_kwargs) -> Tuple[numpy.ndarray, List[Dict]]:
 91def automatic_tracking(
 92    predictor: util.SamPredictor,
 93    segmenter: AutoSegBase,
 94    input_path: Union[Union[os.PathLike, str], np.ndarray],
 95    output_path: Optional[Union[os.PathLike, str]] = None,
 96    embedding_path: Optional[Union[os.PathLike, str]] = None,
 97    key: Optional[str] = None,
 98    tile_shape: Optional[Tuple[int, int]] = None,
 99    halo: Optional[Tuple[int, int]] = None,
100    verbose: bool = True,
101    return_embeddings: bool = False,
102    annotate: bool = False,
103    batch_size: int = 1,
104    mode: str = "greedy",
105    tracking_model: str = "general_2d",
106    **generate_kwargs
107) -> Tuple[np.ndarray, List[Dict]]:
108    """Run automatic tracking for the input timeseries.
109
110    Args:
111        predictor: The Segment Anything model.
112        segmenter: The automatic instance segmentation class.
113        input_path: input_path: The input image file(s). Can either be a single image file (e.g. tif or png),
114            or a container file (e.g. hdf5 or zarr).
115        output_path: The folder where the tracking outputs will be saved in CTC format.
116        embedding_path: The path where the embeddings are cached already / will be saved.
117        key: The key to the input file. This is needed for container files (eg. hdf5 or zarr)
118            or to load several images as 3d volume. Provide a glob patterm, eg. "*.tif", for this case.
119        tile_shape: Shape of the tiles for tiled prediction. By default prediction is run without tiling.
120        halo: Overlap of the tiles for tiled prediction. By default prediction is run without tiling.
121        verbose: Verbosity flag. By default, set to 'True'.
122        return_embeddings: Whether to return the precomputed image embeddings.
123            By default, does not return the embeddings.
124        annotate: Whether to activate the annotator for continue annotation process.
125            By default, does not activate the annotator.
126        batch_size: The batch size to compute image embeddings over tiles / z-planes.
127            By default, does it sequentially, i.e. one after the other.
128        mode: The trackastra linking solver. One of 'greedy_nodiv', 'greedy' or 'ilp'.
129            'ilp' uses the motile solver. By default, set to 'greedy'.
130        tracking_model: The pretrained trackastra model to use. By default, set to 'general_2d'.
131        generate_kwargs: optional keyword arguments for the generate function of the AMG, APG, or AIS class.
132
133    Returns:
134        The tracking result as a timeseries, where each object is labeled by its track id.
135        The lineages representing cell divisions, stored as a dictionary.
136    """
137    # Load the input image file.
138    # We assume that it has to be read from file if it is a str or pathlike.
139    # Otherwise we assume it is a numpy array like object.
140    image_data = util.load_image_data(input_path, key) if isinstance(input_path, (str, os.PathLike)) else input_path
141
142    if (image_data.ndim != 3) and (image_data.ndim != 4 and image_data.shape[-1] != 3):
143        raise ValueError(f"The inputs does not match the shape expectation of 3d inputs: {image_data.shape}")
144
145    gap_closing, min_time_extent = generate_kwargs.get("gap_closing"), generate_kwargs.get("min_time_extent")
146    segmentation, lineage, image_embeddings = automatic_tracking_implementation(
147        image_data,
148        predictor,
149        segmenter,
150        embedding_path=embedding_path,
151        gap_closing=gap_closing,
152        min_time_extent=min_time_extent,
153        tile_shape=tile_shape,
154        halo=halo,
155        verbose=verbose,
156        batch_size=batch_size,
157        mode=mode,
158        tracking_model=tracking_model,
159        return_embeddings=True,
160        output_folder=output_path,
161        **generate_kwargs,
162    )
163
164    if annotate:
165        # TODO We need to support initialization of the tracking annotator with the tracking result for this.
166        raise NotImplementedError("Annotation after running the automated tracking is currently not supported.")
167
168    if return_embeddings:
169        return segmentation, lineage, image_embeddings
170    else:
171        return segmentation, lineage

Run automatic tracking for the input timeseries.

Arguments:
  • predictor: The Segment Anything model.
  • segmenter: The automatic instance segmentation class.
  • input_path: input_path: The input image file(s). Can either be a single image file (e.g. tif or png), or a container file (e.g. hdf5 or zarr).
  • output_path: The folder where the tracking outputs will be saved in CTC format.
  • embedding_path: The path where the embeddings are cached already / will be saved.
  • key: The key to the input file. This is needed for container files (eg. hdf5 or zarr) or to load several images as 3d volume. Provide a glob patterm, eg. "*.tif", for this case.
  • 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, does not return the embeddings.
  • annotate: Whether to activate the annotator for continue annotation process. By default, does not activate the annotator.
  • batch_size: The batch size to compute image embeddings over tiles / z-planes. By default, does it sequentially, i.e. one after the other.
  • 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'.
  • generate_kwargs: optional keyword arguments for the generate function of the AMG, APG, or AIS class.
Returns:

The tracking result as a timeseries, where each object is labeled by its track id. The lineages representing cell divisions, stored as a dictionary.

def automatic_instance_segmentation( predictor: mobile_sam.predictor.SamPredictor, segmenter: micro_sam.util.AutoSegBase, input_path: Union[os.PathLike, str, numpy.ndarray], output_path: Union[str, os.PathLike, NoneType] = None, embedding_path: Union[str, os.PathLike, NoneType] = None, mask_path: Union[os.PathLike, str, numpy.ndarray, NoneType] = None, key: Optional[str] = None, mask_key: Optional[str] = None, ndim: Optional[int] = None, tile_shape: Optional[Tuple[int, int]] = None, halo: Optional[Tuple[int, int]] = None, verbose: bool = True, return_embeddings: bool = False, annotate: bool = False, batch_size: int = 1, **generate_kwargs) -> numpy.ndarray:
174def automatic_instance_segmentation(
175    predictor: util.SamPredictor,
176    segmenter: AutoSegBase,
177    input_path: Union[Union[os.PathLike, str], np.ndarray],
178    output_path: Optional[Union[os.PathLike, str]] = None,
179    embedding_path: Optional[Union[os.PathLike, str]] = None,
180    mask_path: Optional[Union[Union[os.PathLike, str], np.ndarray]] = None,
181    key: Optional[str] = None,
182    mask_key: Optional[str] = None,
183    ndim: Optional[int] = None,
184    tile_shape: Optional[Tuple[int, int]] = None,
185    halo: Optional[Tuple[int, int]] = None,
186    verbose: bool = True,
187    return_embeddings: bool = False,
188    annotate: bool = False,
189    batch_size: int = 1,
190    **generate_kwargs
191) -> np.ndarray:
192    """Run automatic segmentation for the input image.
193
194    Args:
195        predictor: The Segment Anything model.
196        segmenter: The automatic instance segmentation class.
197        input_path: input_path: The input image file(s). Can either be a single image file (e.g. tif or png),
198            or a container file (e.g. hdf5 or zarr).
199        output_path: The output path where the instance segmentations will be saved.
200        embedding_path: The path where the embeddings are cached already / will be saved.
201        mask_path: The path to an optional foreground mask. Areas outside of the foreground will not be processed.
202        key: The key to the input file. This is needed for container files (eg. hdf5 or zarr)
203            or to load several images as 3d volume. Provide a glob patterm, eg. "*.tif", for this case.
204        mask_key: The key to the (optional) foreground mask.
205        ndim: The dimensionality of the data. By default the dimensionality of the data will be used.
206            If you have RGB data you have to specify this explicitly, e.g. pass ndim=2 for 2d segmentation of RGB.
207        tile_shape: Shape of the tiles for tiled prediction. By default prediction is run without tiling.
208        halo: Overlap of the tiles for tiled prediction. By default prediction is run without tiling.
209        verbose: Verbosity flag. By default, set to 'True'.
210        return_embeddings: Whether to return the precomputed image embeddings.
211            By default, does not return the embeddings.
212        annotate: Whether to activate the annotator for continue annotation process.
213            By default, does not activate the annotator.
214        batch_size: The batch size to compute image embeddings over tiles / z-planes.
215            By default, does it sequentially, i.e. one after the other.
216        generate_kwargs: optional keyword arguments for the generate function of the AMG or AIS class.
217
218    Returns:
219        The segmentation result.
220    """
221    # Avoid overwriting already stored segmentations.
222    if output_path is not None:
223        output_path = Path(output_path).with_suffix(".tif")
224        if os.path.exists(output_path):
225            print(f"The segmentation results are already stored at '{os.path.abspath(output_path)}'.")
226            return
227
228    # We assume that it has to be read from file if it is a str or pathlike.
229    # Otherwise we assume it is a numpy array like object.
230    image_data = util.load_image_data(input_path, key) if isinstance(input_path, (str, os.PathLike)) else input_path
231
232    ndim = image_data.ndim if ndim is None else ndim
233
234    # Load the mask defining foreground if it was given.
235    if mask_path is None:
236        mask = None
237    else:
238        mask = util.load_image_data(mask_path, mask_key) if isinstance(mask_path, (str, os.PathLike)) else mask_path
239
240    if ndim == 2:
241        if (image_data.ndim != 2) and (image_data.ndim != 3 and image_data.shape[-1] != 3):
242            raise ValueError(f"The inputs does not match the shape expectation of 2d inputs: {image_data.shape}")
243
244        # Precompute the image embeddings.
245        image_embeddings = precompute_image_embeddings(
246            predictor=predictor,
247            input_=image_data,
248            save_path=embedding_path,
249            ndim=ndim,
250            tile_shape=tile_shape,
251            halo=halo,
252            verbose=verbose,
253            batch_size=batch_size,
254            mask=mask,
255        )
256        initialize_kwargs = dict(image=image_data, image_embeddings=image_embeddings, verbose=verbose)
257        if mask is not None:
258            initialize_kwargs["mask"] = mask
259
260        # If we run AIS with tiling then we use the same tile shape for the watershed postprocessing.
261        # In this case, we also add the batch size to the initialize kwargs,
262        # so that the segmentation decoder can be applied in a batched fashion.
263        if isinstance(segmenter, InstanceSegmentationWithDecoder) and tile_shape is not None:
264            if not isinstance(segmenter, TiledAutomaticPromptGenerator):
265                generate_kwargs.update({"tile_shape": tile_shape, "halo": halo})
266            initialize_kwargs["batch_size"] = batch_size
267
268        segmenter.initialize(**initialize_kwargs)
269        instances = segmenter.generate(**generate_kwargs)
270
271    else:
272        if (image_data.ndim != 3) and (image_data.ndim != 4 and image_data.shape[-1] != 3):
273            raise ValueError(f"The inputs does not match the shape expectation of 3d inputs: {image_data.shape}")
274        if mask is not None:
275            raise NotImplementedError
276
277        instances, image_embeddings = automatic_3d_segmentation(
278            volume=image_data,
279            predictor=predictor,
280            segmentor=segmenter,
281            embedding_path=embedding_path,
282            tile_shape=tile_shape,
283            halo=halo,
284            verbose=verbose,
285            return_embeddings=True,
286            batch_size=batch_size,
287            **generate_kwargs
288        )
289
290    # Before starting to annotate, if at all desired, store the automatic segmentations in the first stage.
291    if output_path is not None:
292        _output_path = _add_suffix_to_output_path(output_path, "_automatic") if annotate else output_path
293        imageio.imwrite(_output_path, instances, compression="zlib")
294        if verbose:
295            print(f"The automatic segmentation results are stored at '{os.path.abspath(_output_path)}'.")
296
297    # Allow opening the automatic segmentation in the annotator for further annotation, if desired.
298    if annotate:
299        from micro_sam.sam_annotator import annotator
300
301        viewer = annotator(
302            image=image_data,
303            ndim=ndim,
304            model_type=predictor.model_name,
305            embedding_path=image_embeddings,  # Providing the precomputed image embeddings.
306            segmentation_result=instances,  # Initializes the automatic segmentation to the annotator.
307            tile_shape=tile_shape,
308            halo=halo,
309            return_viewer=True,  # Returns the viewer, which allows the user to store the updated segmentations.
310        )
311
312        # Start the GUI here
313        import napari
314        napari.run()
315
316        # We extract the segmentation in "committed_objects" layer, where the user either:
317        # a) Performed interactive segmentation / corrections and committed them, OR
318        # b) Did not do anything and closed the annotator, i.e. keeps the segmentations as it is.
319        instances = viewer.layers["committed_objects"].data
320
321        # Save the instance segmentation, if 'output_path' provided.
322        if output_path is not None:
323            imageio.imwrite(output_path, instances, compression="zlib")
324            if verbose:
325                print(f"The final segmentation results are stored at '{os.path.abspath(output_path)}'.")
326
327    if return_embeddings:
328        return instances, image_embeddings
329    else:
330        return instances

Run automatic segmentation for the input image.

Arguments:
  • predictor: The Segment Anything model.
  • segmenter: The automatic instance segmentation class.
  • input_path: input_path: The input image file(s). Can either be a single image file (e.g. tif or png), or a container file (e.g. hdf5 or zarr).
  • output_path: The output path where the instance segmentations will be saved.
  • embedding_path: The path where the embeddings are cached already / will be saved.
  • mask_path: The path to an optional foreground mask. Areas outside of the foreground will not be processed.
  • key: The key to the input file. This is needed for container files (eg. hdf5 or zarr) or to load several images as 3d volume. Provide a glob patterm, eg. "*.tif", for this case.
  • mask_key: The key to the (optional) foreground mask.
  • ndim: The dimensionality of the data. By default the dimensionality of the data will be used. If you have RGB data you have to specify this explicitly, e.g. pass ndim=2 for 2d segmentation of RGB.
  • 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, does not return the embeddings.
  • annotate: Whether to activate the annotator for continue annotation process. By default, does not activate the annotator.
  • batch_size: The batch size to compute image embeddings over tiles / z-planes. By default, does it sequentially, i.e. one after the other.
  • generate_kwargs: optional keyword arguments for the generate function of the AMG or AIS class.
Returns:

The segmentation result.