micro_sam.v1.instance_segmentation
Automated instance segmentation functionality. The classes implemented here extend the automatic instance segmentation from Segment Anything: https://computational-cell-analytics.github.io/micro-sam/micro_sam.html
1"""Automated instance segmentation functionality. 2The classes implemented here extend the automatic instance segmentation from Segment Anything: 3https://computational-cell-analytics.github.io/micro-sam/micro_sam.html 4""" 5 6import os 7import shutil 8import tempfile 9import warnings 10from copy import deepcopy 11from collections import OrderedDict 12from contextlib import contextmanager 13from typing import Any, Dict, Literal, List, Optional, Tuple, Union 14 15import zarr 16import numpy as np 17 18from skimage.measure import regionprops 19from skimage.segmentation import find_boundaries 20 21import segment_anything.utils.amg as amg_utils 22from segment_anything.predictor import SamPredictor 23 24import torch 25from torchvision.ops.boxes import batched_nms, box_area 26 27import elf.parallel as parallel_impl 28from elf.parallel.filters import apply_filter 29from elf.wrapper.generic import ThresholdWrapper 30from elf.wrapper.base import MultiTransformationWrapper 31 32from torch_em.model import UNETR 33from torch_em.util.segmentation import watershed_from_center_and_boundary_distances 34 35from bioimage_cpp.utils import Blocking 36from bioimage_cpp import filters as filter_impl 37 38from .. import util 39from ..util import AutoSegBase 40from .._vendored import batched_mask_to_box, mask_to_rle_pytorch 41from .inference import batched_inference, batched_tiled_inference 42from .util import get_sam_model, precompute_image_embeddings, set_precomputed 43 44# We may change this to 'apg' in version 1.8. 45DEFAULT_SEGMENTATION_MODE_WITH_DECODER = "ais" 46 47# 48# Utility Functionality 49# 50 51 52class _FakeInput: 53 def __init__(self, shape): 54 self.shape = shape 55 56 def __getitem__(self, index): 57 block_shape = tuple(ind.stop - ind.start for ind in index) 58 return np.zeros(block_shape, dtype="float32") 59 60 61# 62# Classes for automatic instance segmentation 63# 64 65 66class AMGBase(AutoSegBase): 67 """Base class for the grid-based (AMG) automatic mask generators.""" 68 def __init__(self): 69 # the state that has to be computed by the 'initialize' method of the child classes 70 self._is_initialized = False 71 self._crop_list = None 72 self._crop_boxes = None 73 self._original_size = None 74 75 @property 76 def crop_list(self): 77 """The list of mask data after initialization. 78 """ 79 return self._crop_list 80 81 @property 82 def crop_boxes(self): 83 """The list of crop boxes. 84 """ 85 return self._crop_boxes 86 87 @property 88 def original_size(self): 89 """The original image size. 90 """ 91 return self._original_size 92 93 def _postprocess_batch( 94 self, 95 data, 96 crop_box, 97 original_size, 98 pred_iou_thresh, 99 stability_score_thresh, 100 box_nms_thresh, 101 ): 102 orig_h, orig_w = original_size 103 104 # filter by predicted IoU 105 if pred_iou_thresh > 0.0: 106 keep_mask = data["iou_preds"] > pred_iou_thresh 107 data.filter(keep_mask) 108 109 # filter by stability score 110 if stability_score_thresh > 0.0: 111 keep_mask = data["stability_score"] >= stability_score_thresh 112 data.filter(keep_mask) 113 114 # filter boxes that touch crop boundaries 115 keep_mask = ~amg_utils.is_box_near_crop_edge(data["boxes"], crop_box, [0, 0, orig_w, orig_h]) 116 if not torch.all(keep_mask): 117 data.filter(keep_mask) 118 119 # remove duplicates within this crop. 120 keep_by_nms = batched_nms( 121 data["boxes"].float(), 122 data["iou_preds"], 123 torch.zeros_like(data["boxes"][:, 0]), # categories 124 iou_threshold=box_nms_thresh, 125 ) 126 data.filter(keep_by_nms) 127 128 # return to the original image frame 129 data["boxes"] = amg_utils.uncrop_boxes_xyxy(data["boxes"], crop_box) 130 data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))]) 131 # the data from embedding based segmentation doesn't have the points 132 # so we skip if the corresponding key can't be found 133 try: 134 data["points"] = amg_utils.uncrop_points(data["points"], crop_box) 135 except KeyError: 136 pass 137 138 return data 139 140 def _postprocess_small_regions(self, mask_data, min_area, nms_thresh): 141 142 if len(mask_data["rles"]) == 0: 143 return mask_data 144 145 # filter small disconnected regions and holes 146 new_masks = [] 147 scores = [] 148 for rle in mask_data["rles"]: 149 mask = amg_utils.rle_to_mask(rle) 150 151 mask, changed = amg_utils.remove_small_regions(mask, min_area, mode="holes") 152 unchanged = not changed 153 mask, changed = amg_utils.remove_small_regions(mask, min_area, mode="islands") 154 unchanged = unchanged and not changed 155 156 new_masks.append(torch.as_tensor(mask, dtype=torch.int).unsqueeze(0)) 157 # give score=0 to changed masks and score=1 to unchanged masks 158 # so NMS will prefer ones that didn't need postprocessing 159 scores.append(float(unchanged)) 160 161 # recalculate boxes and remove any new duplicates 162 masks = torch.cat(new_masks, dim=0) 163 boxes = batched_mask_to_box(masks.to(torch.bool)) # Casting this to boolean as we work with one-hot labels. 164 keep_by_nms = batched_nms( 165 boxes.float(), 166 torch.as_tensor(scores, dtype=torch.float), 167 torch.zeros_like(boxes[:, 0]), # categories 168 iou_threshold=nms_thresh, 169 ) 170 171 # only recalculate RLEs for masks that have changed 172 for i_mask in keep_by_nms: 173 if scores[i_mask] == 0.0: 174 mask_torch = masks[i_mask].unsqueeze(0) 175 # mask_data["rles"][i_mask] = amg_utils.mask_to_rle_pytorch(mask_torch)[0] 176 mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0] 177 mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly 178 mask_data.filter(keep_by_nms) 179 180 return mask_data 181 182 def _postprocess_masks(self, mask_data, min_mask_region_area, box_nms_thresh, crop_nms_thresh, output_mode): 183 # filter small disconnected regions and holes in masks 184 if min_mask_region_area > 0: 185 mask_data = self._postprocess_small_regions( 186 mask_data, 187 min_mask_region_area, 188 max(box_nms_thresh, crop_nms_thresh), 189 ) 190 191 # encode masks 192 if output_mode == "coco_rle": 193 mask_data["segmentations"] = [amg_utils.coco_encode_rle(rle) for rle in mask_data["rles"]] 194 # We require the binary mask output for creating the instance-seg output. 195 elif output_mode in ("binary_mask", "instance_segmentation"): 196 mask_data["segmentations"] = [amg_utils.rle_to_mask(rle) for rle in mask_data["rles"]] 197 elif output_mode == "rle": 198 mask_data["segmentations"] = mask_data["rles"] 199 else: 200 raise ValueError(f"Invalid output mode {output_mode}.") 201 202 # write mask records 203 curr_anns = [] 204 for idx in range(len(mask_data["segmentations"])): 205 ann = { 206 "segmentation": mask_data["segmentations"][idx], 207 "area": amg_utils.area_from_rle(mask_data["rles"][idx]), 208 "bbox": amg_utils.box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(), 209 "predicted_iou": mask_data["iou_preds"][idx].item(), 210 "stability_score": mask_data["stability_score"][idx].item(), 211 "crop_box": amg_utils.box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(), 212 } 213 # the data from embedding based segmentation doesn't have the points 214 # so we skip if the corresponding key can't be found 215 try: 216 ann["point_coords"] = [mask_data["points"][idx].tolist()] 217 except KeyError: 218 pass 219 curr_anns.append(ann) 220 221 return curr_anns 222 223 def _to_mask_data(self, masks, iou_preds, crop_box, original_size, points=None): 224 orig_h, orig_w = original_size 225 226 # serialize predictions and store in MaskData 227 data = amg_utils.MaskData(masks=masks.flatten(0, 1), iou_preds=iou_preds.flatten(0, 1)) 228 if points is not None: 229 data["points"] = torch.as_tensor(points.repeat(masks.shape[1], axis=0), dtype=torch.float) 230 231 del masks 232 233 # calculate the stability scores 234 data["stability_score"] = amg_utils.calculate_stability_score( 235 data["masks"], self._predictor.model.mask_threshold, self._stability_score_offset 236 ) 237 238 # threshold masks and calculate boxes 239 data["masks"] = data["masks"] > self._predictor.model.mask_threshold 240 data["masks"] = data["masks"].type(torch.bool) 241 data["boxes"] = batched_mask_to_box(data["masks"]) 242 243 # compress to RLE 244 data["masks"] = amg_utils.uncrop_masks(data["masks"], crop_box, orig_h, orig_w) 245 # data["rles"] = amg_utils.mask_to_rle_pytorch(data["masks"]) 246 data["rles"] = mask_to_rle_pytorch(data["masks"]) 247 del data["masks"] 248 249 return data 250 251 def get_state(self) -> Dict[str, Any]: 252 """Get the initialized state of the mask generator. 253 254 Returns: 255 State of the mask generator. 256 """ 257 if not self.is_initialized: 258 raise RuntimeError("The state has not been computed yet. Call initialize first.") 259 260 return {"crop_list": self.crop_list, "crop_boxes": self.crop_boxes, "original_size": self.original_size} 261 262 def set_state(self, state: Dict[str, Any]) -> None: 263 """Set the state of the mask generator. 264 265 Args: 266 state: The state of the mask generator, e.g. from serialized state. 267 """ 268 self._crop_list = state["crop_list"] 269 self._crop_boxes = state["crop_boxes"] 270 self._original_size = state["original_size"] 271 self._is_initialized = True 272 273 def clear_state(self): 274 """Clear the state of the mask generator. 275 """ 276 self._crop_list = None 277 self._crop_boxes = None 278 self._original_size = None 279 self._is_initialized = False 280 281 282class AutomaticMaskGenerator(AMGBase): 283 """Generates an instance segmentation without prompts, using a point grid. 284 285 This class implements the same logic as 286 https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/automatic_mask_generator.py 287 It decouples the computationally expensive steps of generating masks from the cheap post-processing operation 288 to filter these masks to enable grid search and interactively changing the post-processing. 289 290 Use this class as follows: 291 ```python 292 amg = AutomaticMaskGenerator(predictor) 293 amg.initialize(image) # Initialize the masks, this takes care of all expensive computations. 294 masks = amg.generate(pred_iou_thresh=0.8) # Generate the masks. This is fast and enables testing parameters 295 ``` 296 297 Args: 298 predictor: The segment anything predictor. 299 points_per_side: The number of points to be sampled along one side of the image. 300 If None, `point_grids` must provide explicit point sampling. By default, set to '32'. 301 points_per_batch: The number of points run simultaneously by the model. 302 Higher numbers may be faster but use more GPU memory. 303 By default, selects '64' for all devices except 'mps' (selects '16' for performance reasons). 304 crop_n_layers: If >0, the mask prediction will be run again on crops of the image. 305 By default, set to '0'. 306 crop_overlap_ratio: Sets the degree to which crops overlap. By default, set to '512 / 1500'. 307 crop_n_points_downscale_factor: How the number of points is downsampled when predicting with crops. 308 By default, set to '1'. 309 point_grids: A list over explicit grids of points used for sampling masks. 310 Normalized to [0, 1] with respect to the image coordinate system. 311 stability_score_offset: The amount to shift the cutoff when calculating the stability score. 312 By default, set to '1.0'. 313 """ 314 def __init__( 315 self, 316 predictor: SamPredictor, 317 points_per_side: Optional[int] = 32, 318 points_per_batch: Optional[int] = None, 319 crop_n_layers: int = 0, 320 crop_overlap_ratio: float = 512 / 1500, 321 crop_n_points_downscale_factor: int = 1, 322 point_grids: Optional[List[np.ndarray]] = None, 323 stability_score_offset: float = 1.0, 324 ): 325 super().__init__() 326 327 if points_per_side is not None: 328 self.point_grids = amg_utils.build_all_layer_point_grids( 329 points_per_side, crop_n_layers, crop_n_points_downscale_factor, 330 ) 331 elif point_grids is not None: 332 self.point_grids = point_grids 333 else: 334 raise ValueError("Can't have both points_per_side and point_grid be None or not None.") 335 336 self._predictor = predictor 337 self._points_per_side = points_per_side 338 339 # we set the points per batch to 16 for mps for performance reasons 340 # and otherwise keep them at the default of 64 341 if points_per_batch is None: 342 points_per_batch = 16 if util.device_type(predictor.device) == "mps" else 64 343 self._points_per_batch = points_per_batch 344 345 self._crop_n_layers = crop_n_layers 346 self._crop_overlap_ratio = crop_overlap_ratio 347 self._crop_n_points_downscale_factor = crop_n_points_downscale_factor 348 self._stability_score_offset = stability_score_offset 349 350 def _process_batch(self, points, im_size, crop_box, original_size): 351 # run model on this batch 352 transformed_points = self._predictor.transform.apply_coords(points, im_size) 353 in_points = torch.as_tensor(transformed_points, device=self._predictor.device, dtype=torch.float) 354 in_labels = torch.ones(in_points.shape[0], dtype=torch.int, device=in_points.device) 355 masks, iou_preds, _ = self._predictor.predict_torch( 356 point_coords=in_points[:, None, :], 357 point_labels=in_labels[:, None], 358 multimask_output=True, 359 return_logits=True, 360 ) 361 data = self._to_mask_data(masks, iou_preds, crop_box, original_size, points=points) 362 del masks 363 return data 364 365 def _process_crop(self, image, crop_box, crop_layer_idx, precomputed_embeddings, pbar_init=None, pbar_update=None): 366 # Crop the image and calculate embeddings. 367 x0, y0, x1, y1 = crop_box 368 cropped_im = image[y0:y1, x0:x1, :] 369 cropped_im_size = cropped_im.shape[:2] 370 371 if not precomputed_embeddings: 372 self._predictor.set_image(cropped_im) 373 374 # Get the points for this crop. 375 points_scale = np.array(cropped_im_size)[None, ::-1] 376 points_for_image = self.point_grids[crop_layer_idx] * points_scale 377 378 # Generate masks for this crop in batches. 379 data = amg_utils.MaskData() 380 n_batches = len(points_for_image) // self._points_per_batch +\ 381 int(len(points_for_image) % self._points_per_batch != 0) 382 if pbar_init is not None: 383 pbar_init(n_batches, "Predict masks for point grid prompts") 384 385 for (points,) in amg_utils.batch_iterator(self._points_per_batch, points_for_image): 386 batch_data = self._process_batch(points, cropped_im_size, crop_box, self.original_size) 387 data.cat(batch_data) 388 del batch_data 389 if pbar_update is not None: 390 pbar_update(1) 391 392 if not precomputed_embeddings: 393 self._predictor.reset_image() 394 395 return data 396 397 @torch.no_grad() 398 def initialize( 399 self, 400 image: np.ndarray, 401 image_embeddings: Optional[util.ImageEmbeddings] = None, 402 i: Optional[int] = None, 403 verbose: bool = False, 404 pbar_init: Optional[callable] = None, 405 pbar_update: Optional[callable] = None, 406 ) -> None: 407 """Initialize image embeddings and masks for an image. 408 409 Args: 410 image: The input image, volume or timeseries. 411 image_embeddings: Optional precomputed image embeddings. 412 See `precompute_image_embeddings` for details. 413 i: Index for the image data. Required if `image` has three spatial dimensions 414 or a time dimension and two spatial dimensions. 415 verbose: Whether to print computation progress. By default, set to 'False'. 416 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 417 Can be used together with pbar_update to handle napari progress bar in other thread. 418 To enable using this function within a threadworker. 419 pbar_update: Callback to update an external progress bar. 420 """ 421 original_size = image.shape[:2] 422 self._original_size = original_size 423 424 crop_boxes, layer_idxs = amg_utils.generate_crop_boxes( 425 original_size, self._crop_n_layers, self._crop_overlap_ratio 426 ) 427 428 # We can set fixed image embeddings if we only have a single crop box (the default setting). 429 # Otherwise we have to recompute the embeddings for each crop and can't precompute. 430 if len(crop_boxes) == 1: 431 if image_embeddings is None: 432 image_embeddings = precompute_image_embeddings(self._predictor, image) 433 set_precomputed(self._predictor, image_embeddings, i=i) 434 precomputed_embeddings = True 435 else: 436 precomputed_embeddings = False 437 438 # we need to cast to the image representation that is compatible with SAM 439 image = util._to_image(image) 440 441 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 442 443 crop_list = [] 444 for crop_box, layer_idx in zip(crop_boxes, layer_idxs): 445 crop_data = self._process_crop( 446 image, crop_box, layer_idx, 447 precomputed_embeddings=precomputed_embeddings, 448 pbar_init=pbar_init, pbar_update=pbar_update, 449 ) 450 crop_list.append(crop_data) 451 pbar_close() 452 453 self._is_initialized = True 454 self._crop_list = crop_list 455 self._crop_boxes = crop_boxes 456 457 @torch.no_grad() 458 def generate( 459 self, 460 pred_iou_thresh: float = 0.88, 461 stability_score_thresh: float = 0.95, 462 box_nms_thresh: float = 0.7, 463 crop_nms_thresh: float = 0.7, 464 min_mask_region_area: int = 0, 465 output_mode: str = "instance_segmentation", 466 with_background: bool = True, 467 ) -> Union[List[Dict[str, Any]], np.ndarray]: 468 """Generate instance segmentation for the currently initialized image. 469 470 Args: 471 pred_iou_thresh: Filter threshold in [0, 1], using the mask quality predicted by the model. 472 By default, set to '0.88'. 473 stability_score_thresh: Filter threshold in [0, 1], using the stability of the mask 474 under changes to the cutoff used to binarize the model prediction. By default, set to '0.95'. 475 box_nms_thresh: The IoU threshold used by nonmax suppression to filter duplicate masks. 476 By default, set to '0.7'. 477 crop_nms_thresh: The IoU threshold used by nonmax suppression to filter duplicate masks between crops. 478 By default, set to '0.7'. 479 min_mask_region_area: Minimal size for the predicted masks. By default, set to '0'. 480 output_mode: The form masks are returned in. Possible values are: 481 - 'binary_mask': Return a list of dictionaries with masks encoded as binary masks. 482 - 'coco_rle': Return a list of dictionaries with run-length encoded masks in MS COCO format. 483 - 'instance_segmentation': Return masks merged into an instance segmentation in a single array. 484 - 'rle': Return a list of dictionaries with run-length encoded masks. 485 By default, set to 'instance_segmentation'. 486 with_background: Whether to remove the largest object, which often covers the background. 487 488 Returns: 489 The segmentation masks. 490 """ 491 if not self.is_initialized: 492 raise RuntimeError("AutomaticMaskGenerator has not been initialized. Call initialize first.") 493 494 data = amg_utils.MaskData() 495 for data_, crop_box in zip(self.crop_list, self.crop_boxes): 496 crop_data = self._postprocess_batch( 497 data=deepcopy(data_), 498 crop_box=crop_box, original_size=self.original_size, 499 pred_iou_thresh=pred_iou_thresh, 500 stability_score_thresh=stability_score_thresh, 501 box_nms_thresh=box_nms_thresh 502 ) 503 data.cat(crop_data) 504 505 if len(self.crop_boxes) > 1 and len(data["crop_boxes"]) > 0: 506 # Prefer masks from smaller crops 507 scores = 1 / box_area(data["crop_boxes"]) 508 scores = scores.to(data["boxes"].device) 509 keep_by_nms = batched_nms( 510 data["boxes"].float(), 511 scores, 512 torch.zeros_like(data["boxes"][:, 0]), # categories 513 iou_threshold=crop_nms_thresh, 514 ) 515 data.filter(keep_by_nms) 516 517 data.to_numpy() 518 masks = self._postprocess_masks(data, min_mask_region_area, box_nms_thresh, crop_nms_thresh, output_mode) 519 if output_mode == "instance_segmentation": 520 shape = next(iter(masks))["segmentation"].shape if len(masks) > 0 else self.original_size 521 masks = util.mask_data_to_segmentation( 522 masks, shape=shape, with_background=with_background, merge_exclusively=False 523 ) 524 return masks 525 526 527# Helper function for tiled embedding computation and checking consistent state. 528def _process_tiled_embeddings(predictor, image, image_embeddings, tile_shape, halo, verbose, batch_size, mask, i): 529 if image_embeddings is None: 530 if tile_shape is None or halo is None: 531 raise ValueError("To compute tiled embeddings the parameters tile_shape and halo have to be passed.") 532 image_embeddings = precompute_image_embeddings( 533 predictor, image, tile_shape=tile_shape, halo=halo, verbose=verbose, batch_size=batch_size, mask=mask, 534 ) 535 536 # Use tile shape and halo from the precomputed embeddings if not given. 537 # Otherwise check that they are consistent. 538 feats = image_embeddings["features"] 539 tile_shape_, halo_ = tuple(feats.attrs["tile_shape"]), tuple(feats.attrs["halo"]) 540 if tile_shape is None: 541 tile_shape = tile_shape_ 542 elif tile_shape != tile_shape_: 543 raise ValueError( 544 f"Inconsistent tile_shape parameter {tile_shape} with precomputed embeedings: {tile_shape_}." 545 ) 546 if halo is None: 547 halo = halo_ 548 elif halo != halo_: 549 raise ValueError(f"Inconsistent halo parameter {halo} with precomputed embeedings: {halo_}.") 550 551 tiles_in_mask = feats.attrs.get("tiles_in_mask", None) 552 if tiles_in_mask is not None and i is not None: 553 tiles_in_mask = tiles_in_mask[str(i)] 554 555 return image_embeddings, tile_shape, halo, tiles_in_mask 556 557 558class TiledAutomaticMaskGenerator(AutomaticMaskGenerator): 559 """Generates an instance segmentation without prompts, using a point grid. 560 561 Implements the same functionality as `AutomaticMaskGenerator` but for tiled embeddings. 562 563 Args: 564 predictor: The Segment Anything predictor. 565 points_per_side: The number of points to be sampled along one side of the image. 566 If None, `point_grids` must provide explicit point sampling. By default, set to '32'. 567 points_per_batch: The number of points run simultaneously by the model. 568 Higher numbers may be faster but use more GPU memory. By default, set to '64'. 569 point_grids: A list over explicit grids of points used for sampling masks. 570 Normalized to [0, 1] with respect to the image coordinate system. 571 stability_score_offset: The amount to shift the cutoff when calculating the stability score. 572 By default, set to '1.0'. 573 """ 574 575 # We only expose the arguments that make sense for the tiled mask generator. 576 # Anything related to crops doesn't make sense, because we re-use that functionality 577 # for tiling, so these parameters wouldn't have any effect. 578 def __init__( 579 self, 580 predictor: SamPredictor, 581 points_per_side: Optional[int] = 32, 582 points_per_batch: int = 64, 583 point_grids: Optional[List[np.ndarray]] = None, 584 stability_score_offset: float = 1.0, 585 ) -> None: 586 super().__init__( 587 predictor=predictor, 588 points_per_side=points_per_side, 589 points_per_batch=points_per_batch, 590 point_grids=point_grids, 591 stability_score_offset=stability_score_offset, 592 ) 593 594 @torch.no_grad() 595 def initialize( 596 self, 597 image: np.ndarray, 598 image_embeddings: Optional[util.ImageEmbeddings] = None, 599 i: Optional[int] = None, 600 tile_shape: Optional[Tuple[int, int]] = None, 601 halo: Optional[Tuple[int, int]] = None, 602 verbose: bool = False, 603 pbar_init: Optional[callable] = None, 604 pbar_update: Optional[callable] = None, 605 batch_size: int = 1, 606 mask: Optional[np.typing.ArrayLike] = None, 607 ) -> None: 608 """Initialize image embeddings and masks for an image. 609 610 Args: 611 image: The input image, volume or timeseries. 612 image_embeddings: Optional precomputed image embeddings. 613 See `precompute_image_embeddings` for details. 614 i: Index for the image data. Required if `image` has three spatial dimensions 615 or a time dimension and two spatial dimensions. 616 tile_shape: The tile shape for embedding prediction. 617 halo: The overlap of between tiles. 618 verbose: Whether to print computation progress. By default, set to 'False'. 619 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 620 Can be used together with pbar_update to handle napari progress bar in other thread. 621 To enable using this function within a threadworker. 622 pbar_update: Callback to update an external progress bar. 623 batch_size: The batch size for image embedding prediction. By default, set to '1'. 624 mask: An optional mask to define areas that are ignored in the segmentation. 625 """ 626 original_size = image.shape[:2] 627 self._original_size = original_size 628 629 self._image_embeddings, tile_shape, halo, tiles_in_mask = _process_tiled_embeddings( 630 self._predictor, image, image_embeddings, tile_shape, halo, 631 verbose=verbose, batch_size=batch_size, mask=mask, i=i, 632 ) 633 634 tiling = Blocking([0, 0], original_size, tile_shape) 635 if tiles_in_mask is None: 636 n_tiles = tiling.number_of_blocks 637 tile_ids = range(n_tiles) 638 else: 639 n_tiles = len(tiles_in_mask) 640 tile_ids = tiles_in_mask 641 642 # The crop box is always the full local tile. 643 tiles = [tiling.get_block_with_halo(tile_id, list(halo)).outer_block for tile_id in tile_ids] 644 crop_boxes = [[tile.begin[1], tile.begin[0], tile.end[1], tile.end[0]] for tile in tiles] 645 646 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 647 pbar_init(n_tiles, "Compute masks for tile") 648 649 # We need to cast to the image representation that is compatible with SAM. 650 image = util._to_image(image) 651 652 mask_data = [] 653 for idx, tile_id in enumerate(tile_ids): 654 # set the pre-computed embeddings for this tile 655 features = image_embeddings["features"][str(tile_id)] 656 tile_embeddings = { 657 "features": features, 658 "input_size": features.attrs["input_size"], 659 "original_size": features.attrs["original_size"], 660 } 661 set_precomputed(self._predictor, tile_embeddings, i) 662 663 # Compute the mask data for this tile and append it 664 this_mask_data = self._process_crop( 665 image, crop_box=crop_boxes[idx], crop_layer_idx=0, precomputed_embeddings=True 666 ) 667 mask_data.append(this_mask_data) 668 pbar_update(1) 669 pbar_close() 670 671 # set the initialized data 672 self._is_initialized = True 673 self._crop_list = mask_data 674 self._crop_boxes = crop_boxes 675 676 677# 678# Instance segmentation functionality based on fine-tuned decoder 679# 680 681 682class DecoderAdapter(torch.nn.Module): 683 """Adapter to contain the UNETR decoder in a single module. 684 685 To apply the decoder on top of pre-computed embeddings for the segmentation functionality. 686 See also: https://github.com/constantinpape/torch-em/blob/main/torch_em/model/unetr.py 687 """ 688 def __init__(self, unetr: torch.nn.Module): 689 super().__init__() 690 691 self.base = unetr.base 692 self.out_conv = unetr.out_conv 693 self.deconv_out = unetr.deconv_out 694 self.decoder_head = unetr.decoder_head 695 self.final_activation = unetr.final_activation 696 self.postprocess_masks = unetr.postprocess_masks 697 698 self.decoder = unetr.decoder 699 self.deconv1 = unetr.deconv1 700 self.deconv2 = unetr.deconv2 701 self.deconv3 = unetr.deconv3 702 self.deconv4 = unetr.deconv4 703 704 def _forward_impl(self, input_): 705 z12 = input_ 706 707 z9 = self.deconv1(z12) 708 z6 = self.deconv2(z9) 709 z3 = self.deconv3(z6) 710 z0 = self.deconv4(z3) 711 712 updated_from_encoder = [z9, z6, z3] 713 714 x = self.base(z12) 715 x = self.decoder(x, encoder_inputs=updated_from_encoder) 716 x = self.deconv_out(x) 717 718 x = torch.cat([x, z0], dim=1) 719 x = self.decoder_head(x) 720 721 x = self.out_conv(x) 722 if self.final_activation is not None: 723 x = self.final_activation(x) 724 return x 725 726 def forward(self, input_, input_shape, original_shape): 727 x = self._forward_impl(input_) 728 x = self.postprocess_masks(x, input_shape, original_shape) 729 return x 730 731 732def get_unetr( 733 image_encoder: torch.nn.Module, 734 decoder_state: Optional[OrderedDict[str, torch.Tensor]] = None, 735 device: Optional[Union[str, torch.device]] = None, 736 out_channels: int = 3, 737 flexible_load_checkpoint: bool = False, 738 final_activation: Optional[str] = "Sigmoid", 739) -> torch.nn.Module: 740 """Get UNETR model for automatic instance segmentation. 741 742 Args: 743 image_encoder: The image encoder of the SAM model. 744 This is used as encoder by the UNETR too. 745 decoder_state: Optional decoder state to initialize the weights of the UNETR decoder. 746 device: The device. By default, automatically chooses the best available device. 747 out_channels: The number of output channels. By default, set to '3'. 748 flexible_load_checkpoint: Whether to allow reinitialization of parameters 749 which could not be found in the provided decoder state. By default, set to 'False'. 750 final_activation: The activation applied to the network output. By default uses a Sigmoid activation. 751 752 Returns: 753 The UNETR model. 754 """ 755 device = util.get_device(device) 756 757 if decoder_state is None: 758 use_conv_transpose = False # By default, we use interpolation for upsampling. 759 else: 760 # From the provided pretrained 'decoder_state', we check whether it uses transposed convolutions. 761 # NOTE: Explanation to the logic below - 762 # - We do this by looking for parameter names that contain '.block.' within the "decoder.samplers" 763 # submodules. This naming convention indicates that transposed convolutions are used, 764 # wrapped inside a custom block module. 765 # - Otherwise '.conv.' appears. It indicates a standard `Conv2d` applied after interpolation for upsampling. 766 use_conv_transpose = any(".block." in k for k in decoder_state.keys() if k.startswith("decoder.samplers")) 767 768 unetr = UNETR( 769 backbone="sam", 770 encoder=image_encoder, 771 out_channels=out_channels, 772 use_sam_stats=True, 773 final_activation=final_activation, 774 use_skip_connection=False, 775 resize_input=True, 776 use_conv_transpose=use_conv_transpose, 777 ) 778 779 if decoder_state is not None: 780 unetr_state_dict = unetr.state_dict() 781 for k, v in unetr_state_dict.items(): 782 if not k.startswith("encoder"): 783 # Whether allow reinitalization of params, if not found or mismatched. 784 if flexible_load_checkpoint: 785 if k in decoder_state: # First check whether the key is available in the provided decoder state. 786 if v.shape != decoder_state[k].shape: # Then check if the sizes mismatch. 787 warnings.warn(f"Shape of '{k}' did not match. Hence, we reinitialize it.") 788 unetr_state_dict[k] = v 789 else: 790 unetr_state_dict[k] = decoder_state[k] 791 else: # Otherwise, allow it to initialize it. 792 warnings.warn(f"Could not find '{k}' in the pretrained state dict. Hence, we reinitialize it.") 793 unetr_state_dict[k] = v 794 795 else: # Be strict on finding the parameter in the decoder state. 796 if k not in decoder_state: 797 raise RuntimeError(f"The parameters for '{k}' could not be found or has a size mismatch.") 798 unetr_state_dict[k] = decoder_state[k] 799 800 unetr.load_state_dict(unetr_state_dict) 801 802 unetr.to(device) 803 return unetr 804 805 806def get_decoder( 807 image_encoder: torch.nn.Module, 808 decoder_state: OrderedDict[str, torch.Tensor], 809 device: Optional[Union[str, torch.device]] = None, 810) -> DecoderAdapter: 811 """Get decoder to predict outputs for automatic instance segmentation 812 813 Args: 814 image_encoder: The image encoder of the SAM model. 815 decoder_state: State to initialize the weights of the UNETR decoder. 816 device: The device. By default, automatically chooses the best available device. 817 818 Returns: 819 The decoder for instance segmentation. 820 """ 821 unetr = get_unetr(image_encoder, decoder_state, device) 822 return DecoderAdapter(unetr) 823 824 825def get_predictor_and_decoder( 826 model_type: str, 827 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 828 device: Optional[Union[str, torch.device]] = None, 829 peft_kwargs: Optional[Dict] = None, 830) -> Tuple[SamPredictor, DecoderAdapter]: 831 """Load the SAM model (predictor) and instance segmentation decoder. 832 833 This requires a checkpoint that contains the state for both predictor 834 and decoder. 835 836 Args: 837 model_type: The type of the image encoder used in the SAM model. 838 checkpoint_path: Path to the checkpoint from which to load the data. 839 device: The device. By default, automatically chooses the best available device. 840 peft_kwargs: Keyword arguments for the PEFT wrapper class. 841 842 Returns: 843 The SAM predictor. 844 The decoder for instance segmentation. 845 """ 846 device = util.get_device(device) 847 predictor, state = get_sam_model( 848 model_type=model_type, 849 checkpoint_path=checkpoint_path, 850 device=device, 851 return_state=True, 852 peft_kwargs=peft_kwargs, 853 ) 854 855 if "decoder_state" not in state: 856 raise ValueError( 857 f"The checkpoint at '{checkpoint_path}' or the chosen model '{model_type}' does not contain a decoder state" 858 ) 859 860 decoder = get_decoder(predictor.model.image_encoder, state["decoder_state"], device) 861 return predictor, decoder 862 863 864@contextmanager 865def _array_or_zarr(shape, dtype, chunks, use_zarr=False): 866 if not use_zarr: 867 yield np.zeros(shape, dtype=dtype) 868 return 869 870 tmpdir = tempfile.mkdtemp(prefix="tmp-zarr-") 871 try: 872 store_path = os.path.join(tmpdir, "tmp.zarr") 873 root = zarr.open_group(store_path, mode="w") 874 arr = root.create_dataset(name="data", shape=shape, dtype=dtype, chunks=chunks) 875 yield arr 876 877 finally: 878 shutil.rmtree(tmpdir, ignore_errors=True) 879 880 881def _watershed_from_center_and_boundary_distances_parallel( 882 center_distances, 883 boundary_distances, 884 foreground_map, 885 center_distance_threshold, 886 boundary_distance_threshold, 887 foreground_threshold, 888 distance_smoothing, 889 min_size, 890 tile_shape, 891 halo, 892 n_threads, 893 verbose=False, 894 optimize_memory=False, 895 segmentation=None, 896): 897 center_distances = apply_filter( 898 center_distances, "gaussianSmoothing", sigma=distance_smoothing, 899 block_shape=tile_shape, n_threads=n_threads 900 ) 901 boundary_distances = apply_filter( 902 boundary_distances, "gaussianSmoothing", sigma=distance_smoothing, 903 block_shape=tile_shape, n_threads=n_threads 904 ) 905 906 fg_mask = ThresholdWrapper(foreground_map, foreground_threshold, operator=np.greater) 907 908 marker_map = MultiTransformationWrapper( 909 np.logical_and, 910 ThresholdWrapper(center_distances, center_distance_threshold, operator=np.less), 911 ThresholdWrapper(boundary_distances, boundary_distance_threshold, operator=np.less), 912 ) 913 marker_map = MultiTransformationWrapper(np.logical_and, marker_map, fg_mask) 914 915 with _array_or_zarr(marker_map.shape, dtype="uint64", chunks=tile_shape, use_zarr=optimize_memory) as markers: 916 markers = parallel_impl.label( 917 marker_map, out=markers, block_shape=tile_shape, n_threads=n_threads, verbose=verbose, 918 ) 919 920 if segmentation is None: 921 segmentation = np.zeros(markers.shape, dtype="uint64") 922 segmentation = parallel_impl.seeded_watershed( 923 boundary_distances, seeds=markers, out=segmentation, block_shape=tile_shape, 924 halo=halo, n_threads=n_threads, verbose=verbose, mask=fg_mask, 925 ) 926 927 if min_size > 0: 928 segmentation = parallel_impl.size_filter( 929 segmentation, out=segmentation, min_size=min_size, 930 block_shape=tile_shape, n_threads=n_threads, verbose=verbose 931 ) 932 933 return segmentation 934 935 936def _apply_smoothing(foreground, foreground_smoothing, tile_shape, n_threads): 937 if tile_shape is None: 938 foreground = filter_impl.gaussian_smoothing(foreground, sigma=foreground_smoothing) 939 else: 940 foreground = apply_filter( 941 foreground, "gaussianSmoothing", sigma=foreground_smoothing, 942 block_shape=tile_shape, n_threads=n_threads 943 ) 944 return foreground 945 946 947class InstanceSegmentationWithDecoder(AutoSegBase): 948 """Generates an instance segmentation without prompts, using a decoder. 949 950 A concrete `AutoSegBase` (like `AutomaticMaskGenerator`), but predicts the segmentation with a 951 decoder instead of grid prompts. 952 953 Use this class as follows: 954 ```python 955 segmenter = InstanceSegmentationWithDecoder(predictor, decoder) 956 segmenter.initialize(image) # Predict the image embeddings and decoder outputs. 957 masks = segmenter.generate(center_distance_threshold=0.75) # Generate the instance segmentation. 958 ``` 959 960 Args: 961 predictor: The segment anything predictor. 962 decoder: The decoder to predict intermediate representations for instance segmentation. 963 """ 964 def __init__(self, predictor: SamPredictor, decoder: torch.nn.Module) -> None: 965 self._predictor = predictor 966 self._decoder = decoder 967 968 # The decoder outputs. 969 self._foreground = None 970 self._center_distances = None 971 self._boundary_distances = None 972 973 self._is_initialized = False 974 975 @torch.no_grad() 976 def initialize( 977 self, 978 image: np.ndarray, 979 image_embeddings: Optional[util.ImageEmbeddings] = None, 980 i: Optional[int] = None, 981 verbose: bool = False, 982 pbar_init: Optional[callable] = None, 983 pbar_update: Optional[callable] = None, 984 ndim: int = 2, 985 ) -> None: 986 """Initialize image embeddings and decoder predictions for an image. 987 988 Args: 989 image: The input image, volume or timeseries. 990 image_embeddings: Optional precomputed image embeddings. 991 See `precompute_image_embeddings` for details. 992 i: Index for the image data. Required if `image` has three spatial dimensions 993 or a time dimension and two spatial dimensions. 994 verbose: Whether to be verbose. By default, set to 'False'. 995 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 996 Can be used together with pbar_update to handle napari progress bar in other thread. 997 To enable using this function within a threadworker. 998 pbar_update: Callback to update an external progress bar. 999 ndim: The dimensionality of the data. If not given will be deduced from the input data. By default, 2. 1000 """ 1001 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 1002 pbar_init(1, "Initialize instance segmentation with decoder") 1003 1004 if image_embeddings is None: 1005 image_embeddings = precompute_image_embeddings( 1006 predictor=self._predictor, input_=image, ndim=ndim, verbose=verbose 1007 ) 1008 1009 # Get the image embeddings from the predictor. 1010 self._predictor = set_precomputed(self._predictor, image_embeddings, i=i) 1011 embeddings = self._predictor.features 1012 input_shape = tuple(self._predictor.input_size) 1013 original_shape = tuple(self._predictor.original_size) 1014 1015 # Run prediction with the UNETR decoder. 1016 output = self._decoder(embeddings, input_shape, original_shape).cpu().numpy().squeeze(0) 1017 assert output.shape[0] == 3, f"{output.shape}" 1018 pbar_update(1) 1019 pbar_close() 1020 1021 # Set the state. 1022 self._foreground = output[0] 1023 self._center_distances = output[1] 1024 self._boundary_distances = output[2] 1025 self._i = i 1026 self._is_initialized = True 1027 1028 def _to_masks(self, segmentation, output_mode): 1029 if output_mode != "binary_mask": 1030 raise ValueError( 1031 f"Output mode {output_mode} is not supported. Choose one of 'instance_segmentation', 'binary_masks'" 1032 ) 1033 1034 props = regionprops(segmentation) 1035 ndim = segmentation.ndim 1036 assert ndim in (2, 3) 1037 1038 shape = segmentation.shape 1039 if ndim == 2: 1040 crop_box = [0, shape[1], 0, shape[0]] 1041 else: 1042 crop_box = [0, shape[2], 0, shape[1], 0, shape[0]] 1043 1044 # go from skimage bbox in format [y0, x0, y1, x1] to SAM format [x0, w, y0, h] 1045 def to_bbox_2d(bbox): 1046 y0, x0 = bbox[0], bbox[1] 1047 w = bbox[3] - x0 1048 h = bbox[2] - y0 1049 return [x0, w, y0, h] 1050 1051 def to_bbox_3d(bbox): 1052 z0, y0, x0 = bbox[0], bbox[1], bbox[2] 1053 w = bbox[5] - x0 1054 h = bbox[4] - y0 1055 d = bbox[3] - y0 1056 return [x0, w, y0, h, z0, d] 1057 1058 to_bbox = to_bbox_2d if ndim == 2 else to_bbox_3d 1059 masks = [ 1060 { 1061 "segmentation": segmentation == prop.label, 1062 "area": prop.area, 1063 "bbox": to_bbox(prop.bbox), 1064 "crop_box": crop_box, 1065 "seg_id": prop.label, 1066 } for prop in props 1067 ] 1068 return masks 1069 1070 def generate( 1071 self, 1072 center_distance_threshold: float = 0.5, 1073 boundary_distance_threshold: float = 0.5, 1074 foreground_threshold: float = 0.5, 1075 foreground_smoothing: float = 1.0, 1076 distance_smoothing: float = 1.6, 1077 min_size: int = 0, 1078 output_mode: str = "instance_segmentation", 1079 tile_shape: Optional[Tuple[int, int]] = None, 1080 halo: Optional[Tuple[int, int]] = None, 1081 n_threads: Optional[int] = None, 1082 optimize_memory: bool = False, 1083 segmentation: Optional[np.ndarray] = None, 1084 ) -> Union[List[Dict[str, Any]], np.ndarray]: 1085 """Generate instance segmentation for the currently initialized image. 1086 1087 Args: 1088 center_distance_threshold: Center distance predictions below this value will be 1089 used to find seeds (intersected with thresholded boundary distance predictions). 1090 By default, set to '0.5'. 1091 boundary_distance_threshold: Boundary distance predictions below this value will be 1092 used to find seeds (intersected with thresholded center distance predictions). 1093 By default, set to '0.5'. 1094 foreground_threshold: Foreground predictions above this value will be used as foreground mask. 1095 By default, set to '0.5'. 1096 foreground_smoothing: Sigma value for smoothing the foreground predictions, to avoid 1097 checkerboard artifacts in the prediction. By default, set to '1.0'. 1098 distance_smoothing: Sigma value for smoothing the distance predictions. 1099 min_size: Minimal object size in the segmentation result. By default, set to '0'. 1100 output_mode: The form masks are returned in. Possible values are: 1101 - 'binary_mask': Return a list of dictionaries with masks encoded as binary masks. 1102 - 'instance_segmentation': Return masks merged into an instance segmentation in a single array. 1103 By default, set to 'instance_segmentation'. 1104 tile_shape: Tile shape for parallelizing the instance segmentation post-processing. 1105 This parameter is independent from the tile shape for computing the embeddings. 1106 If not given then post-processing will not be parallelized. 1107 halo: Halo for parallel post-processing. See also `tile_shape`. 1108 n_threads: Number of threads for parallel post-processing. See also `tile_shape`. 1109 optimize_memory: Whether to optimize the memory consumption by allocating intermediate files. 1110 segmentation: Optional pre-allocated segmentation. 1111 1112 Returns: 1113 The segmentation masks. 1114 """ 1115 if not self.is_initialized: 1116 raise RuntimeError("InstanceSegmentationWithDecoder has not been initialized. Call initialize first.") 1117 1118 if foreground_smoothing > 0: 1119 foreground = _apply_smoothing(self._foreground, foreground_smoothing, tile_shape, n_threads) 1120 else: 1121 foreground = self._foreground 1122 1123 if tile_shape is None: 1124 segmentation = watershed_from_center_and_boundary_distances( 1125 center_distances=self._center_distances, 1126 boundary_distances=self._boundary_distances, 1127 foreground_map=foreground, 1128 center_distance_threshold=center_distance_threshold, 1129 boundary_distance_threshold=boundary_distance_threshold, 1130 foreground_threshold=foreground_threshold, 1131 distance_smoothing=distance_smoothing, 1132 min_size=min_size, 1133 ) 1134 else: 1135 if halo is None: 1136 raise ValueError("You must pass a value for halo if tile_shape is given.") 1137 1138 # Shards are not thread-safe for parallel writing! So if we have shards we have to use them for tiling. 1139 # This is ok in terms efficiency as GPU tiles are small; shards should still be manegable for the watershed. 1140 if isinstance(segmentation, zarr.Array) and getattr(segmentation, "shards", None) is not None: 1141 tile_shape = segmentation.shards 1142 1143 segmentation = _watershed_from_center_and_boundary_distances_parallel( 1144 center_distances=self._center_distances, 1145 boundary_distances=self._boundary_distances, 1146 foreground_map=foreground, 1147 center_distance_threshold=center_distance_threshold, 1148 boundary_distance_threshold=boundary_distance_threshold, 1149 foreground_threshold=foreground_threshold, 1150 distance_smoothing=distance_smoothing, 1151 min_size=min_size, 1152 tile_shape=tile_shape, 1153 halo=halo, 1154 n_threads=n_threads, 1155 verbose=False, 1156 optimize_memory=optimize_memory, 1157 segmentation=segmentation, 1158 ) 1159 1160 if output_mode != "instance_segmentation": 1161 segmentation = self._to_masks(segmentation, output_mode) 1162 return segmentation 1163 1164 def get_state(self) -> Dict[str, Any]: 1165 """Get the initialized state of the instance segmenter. 1166 1167 Returns: 1168 Instance segmentation state. 1169 """ 1170 if not self.is_initialized: 1171 raise RuntimeError("The state has not been computed yet. Call initialize first.") 1172 1173 return { 1174 "foreground": self._foreground, 1175 "center_distances": self._center_distances, 1176 "boundary_distances": self._boundary_distances, 1177 } 1178 1179 def set_state(self, state: Dict[str, Any]) -> None: 1180 """Set the state of the instance segmenter. 1181 1182 Args: 1183 state: The instance segmentation state 1184 """ 1185 self._foreground = state["foreground"] 1186 self._center_distances = state["center_distances"] 1187 self._boundary_distances = state["boundary_distances"] 1188 self._is_initialized = True 1189 1190 def clear_state(self): 1191 """Clear the state of the instance segmenter. 1192 """ 1193 self._foreground = None 1194 self._center_distances = None 1195 self._boundary_distances = None 1196 self._is_initialized = False 1197 1198 1199class TiledInstanceSegmentationWithDecoder(InstanceSegmentationWithDecoder): 1200 """Same as `InstanceSegmentationWithDecoder` but for tiled image embeddings. 1201 """ 1202 1203 # Apply the decoder in a batched fashion, and then perform the resizing independently per output. 1204 # This is necessary, because the individual tiles may have different tile shapes due to border tiles. 1205 def _predict_decoder(self, batched_embeddings, input_shapes, original_shapes): 1206 batched_embeddings = torch.cat(batched_embeddings) 1207 output = self._decoder._forward_impl(batched_embeddings) 1208 1209 batched_output = [] 1210 for x, input_shape, original_shape in zip(output, input_shapes, original_shapes): 1211 x = self._decoder.postprocess_masks(x.unsqueeze(0), input_shape, original_shape).squeeze(0) 1212 batched_output.append(x.cpu().numpy()) 1213 return batched_output 1214 1215 @torch.no_grad() 1216 def initialize( 1217 self, 1218 image: np.ndarray, 1219 image_embeddings: Optional[util.ImageEmbeddings] = None, 1220 i: Optional[int] = None, 1221 tile_shape: Optional[Tuple[int, int]] = None, 1222 halo: Optional[Tuple[int, int]] = None, 1223 verbose: bool = False, 1224 pbar_init: Optional[callable] = None, 1225 pbar_update: Optional[callable] = None, 1226 batch_size: int = 1, 1227 mask: Optional[np.typing.ArrayLike] = None, 1228 ) -> None: 1229 """Initialize image embeddings and decoder predictions for an image. 1230 1231 Args: 1232 image: The input image, volume or timeseries. 1233 image_embeddings: Optional precomputed image embeddings. 1234 See `precompute_image_embeddings` for details. 1235 i: Index for the image data. Required if `image` has three spatial dimensions 1236 or a time dimension and two spatial dimensions. 1237 tile_shape: Shape of the tiles for precomputing image embeddings. 1238 halo: Overlap of the tiles for tiled precomputation of image embeddings. 1239 verbose: Dummy input to be compatible with other function signatures. By default, set to 'False'. 1240 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 1241 Can be used together with pbar_update to handle napari progress bar in other thread. 1242 To enable using this function within a threadworker. 1243 pbar_update: Callback to update an external progress bar. 1244 batch_size: The batch size for image embedding computation and segmentation decoder prediction. 1245 mask: An optional mask to define areas that are ignored in the segmentation. 1246 """ 1247 original_size = image.shape[:2] 1248 self._image_embeddings, tile_shape, halo, tiles_in_mask = _process_tiled_embeddings( 1249 self._predictor, image, image_embeddings, tile_shape, halo, 1250 verbose=verbose, batch_size=batch_size, mask=mask, i=i, 1251 ) 1252 tiling = Blocking([0, 0], original_size, tile_shape) 1253 1254 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 1255 1256 foreground = np.zeros(original_size, dtype="float32") 1257 center_distances = np.zeros(original_size, dtype="float32") 1258 boundary_distances = np.zeros(original_size, dtype="float32") 1259 1260 msg = "Initialize tiled instance segmentation with decoder" 1261 if tiles_in_mask is None: 1262 n_tiles = tiling.number_of_blocks 1263 all_tile_ids = list(range(n_tiles)) 1264 else: 1265 n_tiles = len(tiles_in_mask) 1266 all_tile_ids = tiles_in_mask 1267 msg += " and mask" 1268 1269 n_batches = int(np.ceil(n_tiles / batch_size)) 1270 pbar_init(n_tiles, msg) 1271 tile_ids_for_batches = np.array_split(all_tile_ids, n_batches) 1272 1273 for tile_ids in tile_ids_for_batches: 1274 batched_embeddings, input_shapes, original_shapes = [], [], [] 1275 for tile_id in tile_ids: 1276 # Get the image embeddings from the predictor for this tile. 1277 self._predictor = set_precomputed(self._predictor, self._image_embeddings, i=i, tile_id=tile_id) 1278 1279 batched_embeddings.append(self._predictor.features) 1280 input_shapes.append(tuple(self._predictor.input_size)) 1281 original_shapes.append(tuple(self._predictor.original_size)) 1282 1283 batched_output = self._predict_decoder(batched_embeddings, input_shapes, original_shapes) 1284 1285 for output_id, tile_id in enumerate(tile_ids): 1286 output = batched_output[output_id] 1287 assert output.shape[0] == 3 1288 1289 # Set the predictions in the output for this tile. 1290 block = tiling.get_block_with_halo(tile_id, halo=list(halo)) 1291 local_bb = tuple( 1292 slice(beg, end) for beg, end in zip(block.inner_block_local.begin, block.inner_block_local.end) 1293 ) 1294 inner_bb = tuple(slice(beg, end) for beg, end in zip(block.inner_block.begin, block.inner_block.end)) 1295 1296 foreground[inner_bb] = output[0][local_bb] 1297 center_distances[inner_bb] = output[1][local_bb] 1298 boundary_distances[inner_bb] = output[2][local_bb] 1299 pbar_update(1) 1300 1301 pbar_close() 1302 1303 # Set the state. 1304 self._i = i 1305 self._foreground = foreground 1306 self._center_distances = center_distances 1307 self._boundary_distances = boundary_distances 1308 self._is_initialized = True 1309 1310 1311def _get_centers(segmentation, avoid_image_border=True): 1312 # Not sure if 'find_boundaries' has to be paralellized. 1313 # Compute the distance transform to object bounaries. 1314 boundaries = find_boundaries(segmentation, mode="outer") == 0 1315 # Avoid centroids on the border. 1316 if avoid_image_border: 1317 boundaries[0, :] = False 1318 boundaries[:, 0] = False 1319 boundaries[-1, :] = False 1320 boundaries[:, -1] = False 1321 block_shape = (512, 512) 1322 halo = (16, 16) 1323 distances = parallel_impl.distance_transform(boundaries, halo=halo, block_shape=block_shape) 1324 1325 # Get the maximum coordinate of the distance transform for each id. 1326 props = regionprops(segmentation) 1327 centers = [] 1328 for prop in props: 1329 seg_id = prop.label 1330 # Get the bounding box and mask for this segmentation id. 1331 bounding_box = np.s_[prop.bbox[0]:prop.bbox[2], prop.bbox[1]:prop.bbox[3]] 1332 mask = segmentation[bounding_box] == seg_id 1333 # Restrict the distances to the bounding box. 1334 dist = distances[bounding_box].copy() 1335 # Set the distances outside of the mask to 0. 1336 dist[~mask] = 0 1337 # Find the center coordinate (= distance maximum). 1338 center = np.argmax(dist) 1339 center = np.unravel_index(center, dist.shape) 1340 # Bring the center coordinate back to the full coordinate system. 1341 center = tuple(ce + bb.start for ce, bb in zip(center, bounding_box)) 1342 centers.append(center) 1343 1344 return np.array(centers) 1345 1346 1347def _derive_point_prompts( 1348 foreground: np.ndarray, 1349 center_distances: np.ndarray, 1350 boundary_distances: np.ndarray, 1351 foreground_threshold: float = 0.5, 1352 center_distance_threshold: float = 0.5, 1353 boundary_distance_threshold: float = 0.5, 1354): 1355 bg_mask = foreground < foreground_threshold 1356 hmap_cc = np.logical_and( 1357 center_distances < center_distance_threshold, boundary_distances < boundary_distance_threshold, 1358 ) 1359 hmap_cc[bg_mask] = 0 1360 cc = np.zeros_like(hmap_cc, dtype="uint32") 1361 cc = parallel_impl.label(hmap_cc, out=cc, block_shape=(512, 512)) 1362 prompts = _get_centers(cc) 1363 if len(prompts) == 0: 1364 return None 1365 1366 points = prompts[:, None, ::-1] 1367 labels = np.ones((len(prompts), 1)) 1368 return {"points": points, "point_labels": labels} 1369 1370 1371def _derive_box_prompts(predictions, box_extension): 1372 shape = predictions[0]["segmentation"].shape 1373 bboxes = [pred["bbox"] for pred in predictions] 1374 prompts = [[ 1375 max(x - w * box_extension, 0), 1376 max(y - h * box_extension, 0), 1377 min(x + (1 + box_extension) * w, shape[0]), 1378 min(y + (1 + box_extension) * h, shape[1]), 1379 ] for (x, y, w, h) in bboxes] 1380 return {"boxes": np.array(prompts)} 1381 1382 1383# How the APG masks left after NMS are merged. Several prompts usually land on one object, and the NMS 1384# keeps near duplicates of its masks, so a later duplicate only gets the pixels the earlier one left 1385# free: slivers and rings that would otherwise become objects of their own. Every mask keeps only its 1386# largest free piece, and is dropped when more than a fifth of it is already claimed. +0.005 mSA on 1387# average over ten 2d light microscopy test sets, never worse on one; anything from 0.1 to 0.3 1388# measured the same. 1389APG_MERGE_KWARGS = {"keep_largest_component": True, "max_overlap": 0.2} 1390 1391 1392class AutomaticPromptGenerator(InstanceSegmentationWithDecoder): 1393 """Generates an instance segmentation automatically, using automatically generated prompts from a decoder. 1394 1395 This class is used in the same way as `InstanceSegmentationWithDecoder` and `AutomaticMaskGenerator` 1396 1397 Args: 1398 predictor: The segment anything predictor. 1399 decoder: The derive prompts for automatic instance segmentation. 1400 """ 1401 def generate( 1402 self, 1403 min_size: int = 25, 1404 center_distance_threshold: float = 0.5, 1405 boundary_distance_threshold: float = 0.5, 1406 foreground_threshold: float = 0.5, 1407 multimasking: bool = False, 1408 batch_size: int = 32, 1409 nms_threshold: float = 0.9, 1410 intersection_over_min: bool = False, 1411 output_mode: str = "instance_segmentation", 1412 mask_threshold: Optional[Union[float, str]] = None, 1413 refine_with_box_prompts: bool = False, 1414 prompt_function: Optional[callable] = None, 1415 ) -> Union[List[Dict[str, Any]], np.ndarray]: 1416 """Generate the instance segmentation for the currently initialized image. 1417 1418 The instance segmentation is generated by deriving prompts from the foreground and 1419 distance predictions of the segmentation decoder by thresholding these predictions, 1420 intersecting them, computing connected components, and then using the component's 1421 centers as point prompts. The masks are then filtered via NMS and merged into a segmentation. 1422 1423 Args: 1424 min_size: Minimal object size in the segmentation result. By default, set to '25'. 1425 center_distance_threshold: The threshold for the center distance predictions. 1426 boundary_distance_threshold: The threshold for the boundary distance predictions. 1427 multimasking: Whether to use multi-mask prediction for turning the prompts into masks. 1428 batch_size: The batch size for parallelizing the prediction based on prompts. 1429 nms_threshold: The threshold for non-maximum suppression (NMS). 1430 intersection_over_min: Whether to use the minimum area of the two objects or the 1431 intersection over union area (default) in NMS. 1432 output_mode: The form masks are returned in. Possible values are: 1433 - 'binary_mask': Return a list of dictionaries with masks encoded as binary masks. 1434 - 'instance_segmentation': Return masks merged into an instance segmentation in a single array. 1435 By default, set to 'instance_segmentation'. 1436 mask_threshold: The threshold for turning logits into masks in `micro_sam.v1.inference.batched_inference`.` 1437 refine_with_box_prompts: Whether to refine the mask outputs with another round of box promtps 1438 derived from the segmentations after point prompts. 1439 prompt_function: A custom function for deriving prompts from the segmentation decoder predictions. 1440 If given, the default prompt derivation procedure is not used. Must have the following signature: 1441 ``` 1442 def prompt_function(foreground, center_distances, boundary_distances, **kwargs) 1443 ``` 1444 where `foreground`, `center_distances`, and `boundary_distances` are the respective 1445 predictions from the segmentation decoder. It must returns a dictionary containing 1446 either point, box, or mask prompts in a format compatible with 1447 `micro_sam.v1.inference.batched_inference`. 1448 1449 Returns: 1450 The instance segmentation masks. 1451 """ 1452 if not self.is_initialized: 1453 raise RuntimeError("AutomaticPromptGenerator has not been initialized. Call initialize first.") 1454 foreground, center_distances, boundary_distances =\ 1455 self._foreground, self._center_distances, self._boundary_distances 1456 1457 # 1.) Derive promtps from the decoder predictions. 1458 prompt_function = _derive_point_prompts if prompt_function is None else prompt_function 1459 prompts = prompt_function( 1460 foreground=foreground, 1461 center_distances=center_distances, 1462 boundary_distances=boundary_distances, 1463 foreground_threshold=foreground_threshold, 1464 center_distance_threshold=center_distance_threshold, 1465 boundary_distance_threshold=boundary_distance_threshold, 1466 ) 1467 1468 # 2.) Apply the predictor to the prompts. 1469 if prompts is None: # No prompts were derived, we can't do much further and return empty masks. 1470 return np.zeros(foreground.shape, dtype="uint32") if output_mode == "instance_segmentation" else [] 1471 else: 1472 predictions = batched_inference( 1473 self._predictor, 1474 image=None, 1475 batch_size=batch_size, 1476 return_instance_segmentation=False, 1477 multimasking=multimasking, 1478 mask_threshold=mask_threshold, 1479 i=getattr(self, "_i", None), 1480 **prompts, 1481 ) 1482 1483 # 3.) Refine the segmentation with box prompts. 1484 if refine_with_box_prompts: 1485 box_extension = 0.01 # expose as hyperparam? 1486 prompts = _derive_box_prompts(predictions, box_extension) 1487 predictions = batched_inference( 1488 self._predictor, 1489 image=None, 1490 batch_size=batch_size, 1491 return_instance_segmentation=False, 1492 multimasking=multimasking, 1493 mask_threshold=mask_threshold, 1494 i=getattr(self, "_i", None), 1495 **prompts, 1496 ) 1497 1498 # 4.) Apply non-max suppression to the masks. 1499 segmentation = util.apply_nms( 1500 predictions, min_size=min_size, nms_thresh=nms_threshold, intersection_over_min=intersection_over_min, 1501 **APG_MERGE_KWARGS, 1502 ) 1503 if output_mode != "instance_segmentation": 1504 segmentation = self._to_masks(segmentation, output_mode) 1505 return segmentation 1506 1507 1508class TiledAutomaticPromptGenerator(TiledInstanceSegmentationWithDecoder): 1509 """Same as `AutomaticPromptGenerator` but for tiled image embeddings. 1510 """ 1511 def generate( 1512 self, 1513 min_size: int = 25, 1514 center_distance_threshold: float = 0.5, 1515 boundary_distance_threshold: float = 0.5, 1516 foreground_threshold: float = 0.5, 1517 multimasking: bool = False, 1518 batch_size: int = 32, 1519 nms_threshold: float = 0.9, 1520 intersection_over_min: bool = False, 1521 output_mode: str = "instance_segmentation", 1522 mask_threshold: Optional[Union[float, str]] = None, 1523 refine_with_box_prompts: bool = False, 1524 prompt_function: Optional[callable] = None, 1525 optimize_memory: bool = False, 1526 ) -> List[Dict[str, Any]]: 1527 """Generate tiling-based instance segmentation for the currently initialized image. 1528 1529 Args: 1530 min_size: Minimal object size in the segmentation result. By default, set to '25'. 1531 center_distance_threshold: The threshold for the center distance predictions. 1532 boundary_distance_threshold: The threshold for the boundary distance predictions. 1533 multimasking: Whether to use multi-mask prediction for turning the prompts into masks. 1534 batch_size: The batch size for parallelizing the prediction based on prompts. 1535 nms_threshold: The threshold for non-maximum suppression (NMS). 1536 intersection_over_min: Whether to use the minimum area of the two objects or the 1537 intersection over union area (default) in NMS. 1538 output_mode: The form masks are returned in. Possible values are: 1539 - 'binary_mask': Return a list of dictionaries with masks encoded as binary masks. 1540 - 'instance_segmentation': Return masks merged into an instance segmentation in a single array. 1541 By default, set to 'instance_segmentation'. 1542 mask_threshold: The threshold for turining logits into masks in `micro_sam.v1.inference.batched_inference`.` 1543 refine_with_box_prompts: Whether to refine the mask outputs with another round of box promtps 1544 derived from the segmentations after point prompts. Currently not supported for tiled segmentation. 1545 prompt_function: A custom function for deriving prompts from the segmentation decoder predictions. 1546 If given, the default prompt derivation procedure is not used. Must have the following signature: 1547 ``` 1548 def prompt_function(foreground, center_distances, boundary_distances, **kwargs) 1549 ``` 1550 where `foreground`, `center_distances`, and `boundary_distances` are the respective 1551 predictions from the segmentation decoder. It must returns a dictionary containing 1552 either point, box, or mask prompts in a format compatible with 1553 `micro_sam.v1.inference.batched_inference`. 1554 optimize_memory: Whether to optimize the memory consumption by merging the per-slice 1555 segmentation results immediatly with NMS, rather than running a NMS for all results. 1556 This may lead to a slightly different segmentation result and is only compatible with 1557 `refine_with_box_prompts=False` and `output_mode="instance_segmentation"`. 1558 1559 Returns: 1560 The instance segmentation masks. 1561 """ 1562 if not self.is_initialized: 1563 raise RuntimeError("TiledAutomaticPromptGenerator has not been initialized. Call initialize first.") 1564 if optimize_memory and (output_mode != "instance_segmentation" or refine_with_box_prompts): 1565 raise ValueError("Invalid settings") 1566 foreground, center_distances, boundary_distances =\ 1567 self._foreground, self._center_distances, self._boundary_distances 1568 1569 # 1.) Derive promtps from the decoder predictions. 1570 prompt_function = _derive_point_prompts if prompt_function is None else prompt_function 1571 prompts = prompt_function( 1572 foreground, 1573 center_distances, 1574 boundary_distances, 1575 foreground_threshold=foreground_threshold, 1576 center_distance_threshold=center_distance_threshold, 1577 boundary_distance_threshold=boundary_distance_threshold, 1578 ) 1579 1580 # 2.) Apply the predictor to the prompts. 1581 shape = foreground.shape 1582 if prompts is None: # No prompts were derived, we can't do much further and return empty masks. 1583 return np.zeros(shape, dtype="uint32") if output_mode == "instance_segmentation" else [] 1584 else: 1585 if optimize_memory: 1586 prompts.update(dict( 1587 min_size=min_size, nms_thresh=nms_threshold, intersection_over_min=intersection_over_min, 1588 **APG_MERGE_KWARGS, 1589 )) 1590 predictions = batched_tiled_inference( 1591 self._predictor, 1592 image=None, 1593 batch_size=batch_size, 1594 image_embeddings=self._image_embeddings, 1595 return_instance_segmentation=False, 1596 multimasking=multimasking, 1597 optimize_memory=optimize_memory, 1598 i=getattr(self, "_i", None), 1599 **prompts 1600 ) 1601 # Optimize memory directly returns an instance segmentation and does not 1602 # allow for any further refinements. 1603 if optimize_memory: 1604 return predictions 1605 1606 # 3.) Refine the segmentation with box prompts. 1607 if refine_with_box_prompts: 1608 # TODO 1609 raise NotImplementedError 1610 1611 # 4.) Apply non-max suppression to the masks. 1612 segmentation = util.apply_nms( 1613 predictions, shape=shape, min_size=min_size, nms_thresh=nms_threshold, 1614 intersection_over_min=intersection_over_min, **APG_MERGE_KWARGS, 1615 ) 1616 if output_mode != "instance_segmentation": 1617 segmentation = self._to_masks(segmentation, output_mode) 1618 return segmentation 1619 1620 # Set state and get state are not implemented yet, as this generator relies on having the image embeddings 1621 # in the state. However, they should not be serialized here and we have to address this a bit differently. 1622 def get_state(self): 1623 """@private 1624 """ 1625 raise NotImplementedError 1626 1627 def set_state(self, state): 1628 """@private 1629 """ 1630 raise NotImplementedError 1631 1632 1633def get_instance_segmentation_generator( 1634 predictor: SamPredictor, 1635 is_tiled: bool, 1636 decoder: Optional[torch.nn.Module] = None, 1637 segmentation_mode: Optional[Literal["amg", "ais", "apg"]] = None, 1638 **kwargs, 1639) -> AutoSegBase: 1640 f"""Get the automatic mask generator. 1641 1642 Args: 1643 predictor: The segment anything predictor. 1644 is_tiled: Whether tiled embeddings are used. 1645 decoder: Decoder to predict instacne segmmentation. 1646 segmentation_mode: The segmentation mode. One of 'amg', 'ais', or 'apg'. 1647 By default, '{DEFAULT_SEGMENTATION_MODE_WITH_DECODER}' is used if a decoder is passed, 1648 otherwise 'amg' is used. 1649 kwargs: The keyword arguments of the segmentation genetator class. 1650 1651 Returns: 1652 The segmentation generator instance. 1653 """ 1654 # Choose the segmentation decoder default depending on whether we have a decoder. 1655 if segmentation_mode is None: 1656 segmentation_mode = "amg" if decoder is None else DEFAULT_SEGMENTATION_MODE_WITH_DECODER 1657 1658 if segmentation_mode.lower() == "amg": 1659 segmenter_class = TiledAutomaticMaskGenerator if is_tiled else AutomaticMaskGenerator 1660 segmenter = segmenter_class(predictor, **kwargs) 1661 elif segmentation_mode.lower() == "ais": 1662 assert decoder is not None 1663 segmenter_class = TiledInstanceSegmentationWithDecoder if is_tiled else InstanceSegmentationWithDecoder 1664 segmenter = segmenter_class(predictor, decoder, **kwargs) 1665 elif segmentation_mode.lower() == "apg": 1666 assert decoder is not None 1667 segmenter_class = TiledAutomaticPromptGenerator if is_tiled else AutomaticPromptGenerator 1668 segmenter = segmenter_class(predictor, decoder, **kwargs) 1669 else: 1670 raise ValueError(f"Invalid segmentation_mode: {segmentation_mode}. Choose one of 'amg', 'ais', or 'apg'.") 1671 1672 return segmenter
67class AMGBase(AutoSegBase): 68 """Base class for the grid-based (AMG) automatic mask generators.""" 69 def __init__(self): 70 # the state that has to be computed by the 'initialize' method of the child classes 71 self._is_initialized = False 72 self._crop_list = None 73 self._crop_boxes = None 74 self._original_size = None 75 76 @property 77 def crop_list(self): 78 """The list of mask data after initialization. 79 """ 80 return self._crop_list 81 82 @property 83 def crop_boxes(self): 84 """The list of crop boxes. 85 """ 86 return self._crop_boxes 87 88 @property 89 def original_size(self): 90 """The original image size. 91 """ 92 return self._original_size 93 94 def _postprocess_batch( 95 self, 96 data, 97 crop_box, 98 original_size, 99 pred_iou_thresh, 100 stability_score_thresh, 101 box_nms_thresh, 102 ): 103 orig_h, orig_w = original_size 104 105 # filter by predicted IoU 106 if pred_iou_thresh > 0.0: 107 keep_mask = data["iou_preds"] > pred_iou_thresh 108 data.filter(keep_mask) 109 110 # filter by stability score 111 if stability_score_thresh > 0.0: 112 keep_mask = data["stability_score"] >= stability_score_thresh 113 data.filter(keep_mask) 114 115 # filter boxes that touch crop boundaries 116 keep_mask = ~amg_utils.is_box_near_crop_edge(data["boxes"], crop_box, [0, 0, orig_w, orig_h]) 117 if not torch.all(keep_mask): 118 data.filter(keep_mask) 119 120 # remove duplicates within this crop. 121 keep_by_nms = batched_nms( 122 data["boxes"].float(), 123 data["iou_preds"], 124 torch.zeros_like(data["boxes"][:, 0]), # categories 125 iou_threshold=box_nms_thresh, 126 ) 127 data.filter(keep_by_nms) 128 129 # return to the original image frame 130 data["boxes"] = amg_utils.uncrop_boxes_xyxy(data["boxes"], crop_box) 131 data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))]) 132 # the data from embedding based segmentation doesn't have the points 133 # so we skip if the corresponding key can't be found 134 try: 135 data["points"] = amg_utils.uncrop_points(data["points"], crop_box) 136 except KeyError: 137 pass 138 139 return data 140 141 def _postprocess_small_regions(self, mask_data, min_area, nms_thresh): 142 143 if len(mask_data["rles"]) == 0: 144 return mask_data 145 146 # filter small disconnected regions and holes 147 new_masks = [] 148 scores = [] 149 for rle in mask_data["rles"]: 150 mask = amg_utils.rle_to_mask(rle) 151 152 mask, changed = amg_utils.remove_small_regions(mask, min_area, mode="holes") 153 unchanged = not changed 154 mask, changed = amg_utils.remove_small_regions(mask, min_area, mode="islands") 155 unchanged = unchanged and not changed 156 157 new_masks.append(torch.as_tensor(mask, dtype=torch.int).unsqueeze(0)) 158 # give score=0 to changed masks and score=1 to unchanged masks 159 # so NMS will prefer ones that didn't need postprocessing 160 scores.append(float(unchanged)) 161 162 # recalculate boxes and remove any new duplicates 163 masks = torch.cat(new_masks, dim=0) 164 boxes = batched_mask_to_box(masks.to(torch.bool)) # Casting this to boolean as we work with one-hot labels. 165 keep_by_nms = batched_nms( 166 boxes.float(), 167 torch.as_tensor(scores, dtype=torch.float), 168 torch.zeros_like(boxes[:, 0]), # categories 169 iou_threshold=nms_thresh, 170 ) 171 172 # only recalculate RLEs for masks that have changed 173 for i_mask in keep_by_nms: 174 if scores[i_mask] == 0.0: 175 mask_torch = masks[i_mask].unsqueeze(0) 176 # mask_data["rles"][i_mask] = amg_utils.mask_to_rle_pytorch(mask_torch)[0] 177 mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0] 178 mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly 179 mask_data.filter(keep_by_nms) 180 181 return mask_data 182 183 def _postprocess_masks(self, mask_data, min_mask_region_area, box_nms_thresh, crop_nms_thresh, output_mode): 184 # filter small disconnected regions and holes in masks 185 if min_mask_region_area > 0: 186 mask_data = self._postprocess_small_regions( 187 mask_data, 188 min_mask_region_area, 189 max(box_nms_thresh, crop_nms_thresh), 190 ) 191 192 # encode masks 193 if output_mode == "coco_rle": 194 mask_data["segmentations"] = [amg_utils.coco_encode_rle(rle) for rle in mask_data["rles"]] 195 # We require the binary mask output for creating the instance-seg output. 196 elif output_mode in ("binary_mask", "instance_segmentation"): 197 mask_data["segmentations"] = [amg_utils.rle_to_mask(rle) for rle in mask_data["rles"]] 198 elif output_mode == "rle": 199 mask_data["segmentations"] = mask_data["rles"] 200 else: 201 raise ValueError(f"Invalid output mode {output_mode}.") 202 203 # write mask records 204 curr_anns = [] 205 for idx in range(len(mask_data["segmentations"])): 206 ann = { 207 "segmentation": mask_data["segmentations"][idx], 208 "area": amg_utils.area_from_rle(mask_data["rles"][idx]), 209 "bbox": amg_utils.box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(), 210 "predicted_iou": mask_data["iou_preds"][idx].item(), 211 "stability_score": mask_data["stability_score"][idx].item(), 212 "crop_box": amg_utils.box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(), 213 } 214 # the data from embedding based segmentation doesn't have the points 215 # so we skip if the corresponding key can't be found 216 try: 217 ann["point_coords"] = [mask_data["points"][idx].tolist()] 218 except KeyError: 219 pass 220 curr_anns.append(ann) 221 222 return curr_anns 223 224 def _to_mask_data(self, masks, iou_preds, crop_box, original_size, points=None): 225 orig_h, orig_w = original_size 226 227 # serialize predictions and store in MaskData 228 data = amg_utils.MaskData(masks=masks.flatten(0, 1), iou_preds=iou_preds.flatten(0, 1)) 229 if points is not None: 230 data["points"] = torch.as_tensor(points.repeat(masks.shape[1], axis=0), dtype=torch.float) 231 232 del masks 233 234 # calculate the stability scores 235 data["stability_score"] = amg_utils.calculate_stability_score( 236 data["masks"], self._predictor.model.mask_threshold, self._stability_score_offset 237 ) 238 239 # threshold masks and calculate boxes 240 data["masks"] = data["masks"] > self._predictor.model.mask_threshold 241 data["masks"] = data["masks"].type(torch.bool) 242 data["boxes"] = batched_mask_to_box(data["masks"]) 243 244 # compress to RLE 245 data["masks"] = amg_utils.uncrop_masks(data["masks"], crop_box, orig_h, orig_w) 246 # data["rles"] = amg_utils.mask_to_rle_pytorch(data["masks"]) 247 data["rles"] = mask_to_rle_pytorch(data["masks"]) 248 del data["masks"] 249 250 return data 251 252 def get_state(self) -> Dict[str, Any]: 253 """Get the initialized state of the mask generator. 254 255 Returns: 256 State of the mask generator. 257 """ 258 if not self.is_initialized: 259 raise RuntimeError("The state has not been computed yet. Call initialize first.") 260 261 return {"crop_list": self.crop_list, "crop_boxes": self.crop_boxes, "original_size": self.original_size} 262 263 def set_state(self, state: Dict[str, Any]) -> None: 264 """Set the state of the mask generator. 265 266 Args: 267 state: The state of the mask generator, e.g. from serialized state. 268 """ 269 self._crop_list = state["crop_list"] 270 self._crop_boxes = state["crop_boxes"] 271 self._original_size = state["original_size"] 272 self._is_initialized = True 273 274 def clear_state(self): 275 """Clear the state of the mask generator. 276 """ 277 self._crop_list = None 278 self._crop_boxes = None 279 self._original_size = None 280 self._is_initialized = False
Base class for the grid-based (AMG) automatic mask generators.
76 @property 77 def crop_list(self): 78 """The list of mask data after initialization. 79 """ 80 return self._crop_list
The list of mask data after initialization.
82 @property 83 def crop_boxes(self): 84 """The list of crop boxes. 85 """ 86 return self._crop_boxes
The list of crop boxes.
88 @property 89 def original_size(self): 90 """The original image size. 91 """ 92 return self._original_size
The original image size.
252 def get_state(self) -> Dict[str, Any]: 253 """Get the initialized state of the mask generator. 254 255 Returns: 256 State of the mask generator. 257 """ 258 if not self.is_initialized: 259 raise RuntimeError("The state has not been computed yet. Call initialize first.") 260 261 return {"crop_list": self.crop_list, "crop_boxes": self.crop_boxes, "original_size": self.original_size}
Get the initialized state of the mask generator.
Returns:
State of the mask generator.
263 def set_state(self, state: Dict[str, Any]) -> None: 264 """Set the state of the mask generator. 265 266 Args: 267 state: The state of the mask generator, e.g. from serialized state. 268 """ 269 self._crop_list = state["crop_list"] 270 self._crop_boxes = state["crop_boxes"] 271 self._original_size = state["original_size"] 272 self._is_initialized = True
Set the state of the mask generator.
Arguments:
- state: The state of the mask generator, e.g. from serialized state.
274 def clear_state(self): 275 """Clear the state of the mask generator. 276 """ 277 self._crop_list = None 278 self._crop_boxes = None 279 self._original_size = None 280 self._is_initialized = False
Clear the state of the mask generator.
Inherited Members
283class AutomaticMaskGenerator(AMGBase): 284 """Generates an instance segmentation without prompts, using a point grid. 285 286 This class implements the same logic as 287 https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/automatic_mask_generator.py 288 It decouples the computationally expensive steps of generating masks from the cheap post-processing operation 289 to filter these masks to enable grid search and interactively changing the post-processing. 290 291 Use this class as follows: 292 ```python 293 amg = AutomaticMaskGenerator(predictor) 294 amg.initialize(image) # Initialize the masks, this takes care of all expensive computations. 295 masks = amg.generate(pred_iou_thresh=0.8) # Generate the masks. This is fast and enables testing parameters 296 ``` 297 298 Args: 299 predictor: The segment anything predictor. 300 points_per_side: The number of points to be sampled along one side of the image. 301 If None, `point_grids` must provide explicit point sampling. By default, set to '32'. 302 points_per_batch: The number of points run simultaneously by the model. 303 Higher numbers may be faster but use more GPU memory. 304 By default, selects '64' for all devices except 'mps' (selects '16' for performance reasons). 305 crop_n_layers: If >0, the mask prediction will be run again on crops of the image. 306 By default, set to '0'. 307 crop_overlap_ratio: Sets the degree to which crops overlap. By default, set to '512 / 1500'. 308 crop_n_points_downscale_factor: How the number of points is downsampled when predicting with crops. 309 By default, set to '1'. 310 point_grids: A list over explicit grids of points used for sampling masks. 311 Normalized to [0, 1] with respect to the image coordinate system. 312 stability_score_offset: The amount to shift the cutoff when calculating the stability score. 313 By default, set to '1.0'. 314 """ 315 def __init__( 316 self, 317 predictor: SamPredictor, 318 points_per_side: Optional[int] = 32, 319 points_per_batch: Optional[int] = None, 320 crop_n_layers: int = 0, 321 crop_overlap_ratio: float = 512 / 1500, 322 crop_n_points_downscale_factor: int = 1, 323 point_grids: Optional[List[np.ndarray]] = None, 324 stability_score_offset: float = 1.0, 325 ): 326 super().__init__() 327 328 if points_per_side is not None: 329 self.point_grids = amg_utils.build_all_layer_point_grids( 330 points_per_side, crop_n_layers, crop_n_points_downscale_factor, 331 ) 332 elif point_grids is not None: 333 self.point_grids = point_grids 334 else: 335 raise ValueError("Can't have both points_per_side and point_grid be None or not None.") 336 337 self._predictor = predictor 338 self._points_per_side = points_per_side 339 340 # we set the points per batch to 16 for mps for performance reasons 341 # and otherwise keep them at the default of 64 342 if points_per_batch is None: 343 points_per_batch = 16 if util.device_type(predictor.device) == "mps" else 64 344 self._points_per_batch = points_per_batch 345 346 self._crop_n_layers = crop_n_layers 347 self._crop_overlap_ratio = crop_overlap_ratio 348 self._crop_n_points_downscale_factor = crop_n_points_downscale_factor 349 self._stability_score_offset = stability_score_offset 350 351 def _process_batch(self, points, im_size, crop_box, original_size): 352 # run model on this batch 353 transformed_points = self._predictor.transform.apply_coords(points, im_size) 354 in_points = torch.as_tensor(transformed_points, device=self._predictor.device, dtype=torch.float) 355 in_labels = torch.ones(in_points.shape[0], dtype=torch.int, device=in_points.device) 356 masks, iou_preds, _ = self._predictor.predict_torch( 357 point_coords=in_points[:, None, :], 358 point_labels=in_labels[:, None], 359 multimask_output=True, 360 return_logits=True, 361 ) 362 data = self._to_mask_data(masks, iou_preds, crop_box, original_size, points=points) 363 del masks 364 return data 365 366 def _process_crop(self, image, crop_box, crop_layer_idx, precomputed_embeddings, pbar_init=None, pbar_update=None): 367 # Crop the image and calculate embeddings. 368 x0, y0, x1, y1 = crop_box 369 cropped_im = image[y0:y1, x0:x1, :] 370 cropped_im_size = cropped_im.shape[:2] 371 372 if not precomputed_embeddings: 373 self._predictor.set_image(cropped_im) 374 375 # Get the points for this crop. 376 points_scale = np.array(cropped_im_size)[None, ::-1] 377 points_for_image = self.point_grids[crop_layer_idx] * points_scale 378 379 # Generate masks for this crop in batches. 380 data = amg_utils.MaskData() 381 n_batches = len(points_for_image) // self._points_per_batch +\ 382 int(len(points_for_image) % self._points_per_batch != 0) 383 if pbar_init is not None: 384 pbar_init(n_batches, "Predict masks for point grid prompts") 385 386 for (points,) in amg_utils.batch_iterator(self._points_per_batch, points_for_image): 387 batch_data = self._process_batch(points, cropped_im_size, crop_box, self.original_size) 388 data.cat(batch_data) 389 del batch_data 390 if pbar_update is not None: 391 pbar_update(1) 392 393 if not precomputed_embeddings: 394 self._predictor.reset_image() 395 396 return data 397 398 @torch.no_grad() 399 def initialize( 400 self, 401 image: np.ndarray, 402 image_embeddings: Optional[util.ImageEmbeddings] = None, 403 i: Optional[int] = None, 404 verbose: bool = False, 405 pbar_init: Optional[callable] = None, 406 pbar_update: Optional[callable] = None, 407 ) -> None: 408 """Initialize image embeddings and masks for an image. 409 410 Args: 411 image: The input image, volume or timeseries. 412 image_embeddings: Optional precomputed image embeddings. 413 See `precompute_image_embeddings` for details. 414 i: Index for the image data. Required if `image` has three spatial dimensions 415 or a time dimension and two spatial dimensions. 416 verbose: Whether to print computation progress. By default, set to 'False'. 417 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 418 Can be used together with pbar_update to handle napari progress bar in other thread. 419 To enable using this function within a threadworker. 420 pbar_update: Callback to update an external progress bar. 421 """ 422 original_size = image.shape[:2] 423 self._original_size = original_size 424 425 crop_boxes, layer_idxs = amg_utils.generate_crop_boxes( 426 original_size, self._crop_n_layers, self._crop_overlap_ratio 427 ) 428 429 # We can set fixed image embeddings if we only have a single crop box (the default setting). 430 # Otherwise we have to recompute the embeddings for each crop and can't precompute. 431 if len(crop_boxes) == 1: 432 if image_embeddings is None: 433 image_embeddings = precompute_image_embeddings(self._predictor, image) 434 set_precomputed(self._predictor, image_embeddings, i=i) 435 precomputed_embeddings = True 436 else: 437 precomputed_embeddings = False 438 439 # we need to cast to the image representation that is compatible with SAM 440 image = util._to_image(image) 441 442 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 443 444 crop_list = [] 445 for crop_box, layer_idx in zip(crop_boxes, layer_idxs): 446 crop_data = self._process_crop( 447 image, crop_box, layer_idx, 448 precomputed_embeddings=precomputed_embeddings, 449 pbar_init=pbar_init, pbar_update=pbar_update, 450 ) 451 crop_list.append(crop_data) 452 pbar_close() 453 454 self._is_initialized = True 455 self._crop_list = crop_list 456 self._crop_boxes = crop_boxes 457 458 @torch.no_grad() 459 def generate( 460 self, 461 pred_iou_thresh: float = 0.88, 462 stability_score_thresh: float = 0.95, 463 box_nms_thresh: float = 0.7, 464 crop_nms_thresh: float = 0.7, 465 min_mask_region_area: int = 0, 466 output_mode: str = "instance_segmentation", 467 with_background: bool = True, 468 ) -> Union[List[Dict[str, Any]], np.ndarray]: 469 """Generate instance segmentation for the currently initialized image. 470 471 Args: 472 pred_iou_thresh: Filter threshold in [0, 1], using the mask quality predicted by the model. 473 By default, set to '0.88'. 474 stability_score_thresh: Filter threshold in [0, 1], using the stability of the mask 475 under changes to the cutoff used to binarize the model prediction. By default, set to '0.95'. 476 box_nms_thresh: The IoU threshold used by nonmax suppression to filter duplicate masks. 477 By default, set to '0.7'. 478 crop_nms_thresh: The IoU threshold used by nonmax suppression to filter duplicate masks between crops. 479 By default, set to '0.7'. 480 min_mask_region_area: Minimal size for the predicted masks. By default, set to '0'. 481 output_mode: The form masks are returned in. Possible values are: 482 - 'binary_mask': Return a list of dictionaries with masks encoded as binary masks. 483 - 'coco_rle': Return a list of dictionaries with run-length encoded masks in MS COCO format. 484 - 'instance_segmentation': Return masks merged into an instance segmentation in a single array. 485 - 'rle': Return a list of dictionaries with run-length encoded masks. 486 By default, set to 'instance_segmentation'. 487 with_background: Whether to remove the largest object, which often covers the background. 488 489 Returns: 490 The segmentation masks. 491 """ 492 if not self.is_initialized: 493 raise RuntimeError("AutomaticMaskGenerator has not been initialized. Call initialize first.") 494 495 data = amg_utils.MaskData() 496 for data_, crop_box in zip(self.crop_list, self.crop_boxes): 497 crop_data = self._postprocess_batch( 498 data=deepcopy(data_), 499 crop_box=crop_box, original_size=self.original_size, 500 pred_iou_thresh=pred_iou_thresh, 501 stability_score_thresh=stability_score_thresh, 502 box_nms_thresh=box_nms_thresh 503 ) 504 data.cat(crop_data) 505 506 if len(self.crop_boxes) > 1 and len(data["crop_boxes"]) > 0: 507 # Prefer masks from smaller crops 508 scores = 1 / box_area(data["crop_boxes"]) 509 scores = scores.to(data["boxes"].device) 510 keep_by_nms = batched_nms( 511 data["boxes"].float(), 512 scores, 513 torch.zeros_like(data["boxes"][:, 0]), # categories 514 iou_threshold=crop_nms_thresh, 515 ) 516 data.filter(keep_by_nms) 517 518 data.to_numpy() 519 masks = self._postprocess_masks(data, min_mask_region_area, box_nms_thresh, crop_nms_thresh, output_mode) 520 if output_mode == "instance_segmentation": 521 shape = next(iter(masks))["segmentation"].shape if len(masks) > 0 else self.original_size 522 masks = util.mask_data_to_segmentation( 523 masks, shape=shape, with_background=with_background, merge_exclusively=False 524 ) 525 return masks
Generates an instance segmentation without prompts, using a point grid.
This class implements the same logic as https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/automatic_mask_generator.py It decouples the computationally expensive steps of generating masks from the cheap post-processing operation to filter these masks to enable grid search and interactively changing the post-processing.
Use this class as follows:
amg = AutomaticMaskGenerator(predictor)
amg.initialize(image) # Initialize the masks, this takes care of all expensive computations.
masks = amg.generate(pred_iou_thresh=0.8) # Generate the masks. This is fast and enables testing parameters
Arguments:
- predictor: The segment anything predictor.
- points_per_side: The number of points to be sampled along one side of the image.
If None,
point_gridsmust provide explicit point sampling. By default, set to '32'. - points_per_batch: The number of points run simultaneously by the model. Higher numbers may be faster but use more GPU memory. By default, selects '64' for all devices except 'mps' (selects '16' for performance reasons).
- crop_n_layers: If >0, the mask prediction will be run again on crops of the image. By default, set to '0'.
- crop_overlap_ratio: Sets the degree to which crops overlap. By default, set to '512 / 1500'.
- crop_n_points_downscale_factor: How the number of points is downsampled when predicting with crops. By default, set to '1'.
- point_grids: A list over explicit grids of points used for sampling masks. Normalized to [0, 1] with respect to the image coordinate system.
- stability_score_offset: The amount to shift the cutoff when calculating the stability score. By default, set to '1.0'.
315 def __init__( 316 self, 317 predictor: SamPredictor, 318 points_per_side: Optional[int] = 32, 319 points_per_batch: Optional[int] = None, 320 crop_n_layers: int = 0, 321 crop_overlap_ratio: float = 512 / 1500, 322 crop_n_points_downscale_factor: int = 1, 323 point_grids: Optional[List[np.ndarray]] = None, 324 stability_score_offset: float = 1.0, 325 ): 326 super().__init__() 327 328 if points_per_side is not None: 329 self.point_grids = amg_utils.build_all_layer_point_grids( 330 points_per_side, crop_n_layers, crop_n_points_downscale_factor, 331 ) 332 elif point_grids is not None: 333 self.point_grids = point_grids 334 else: 335 raise ValueError("Can't have both points_per_side and point_grid be None or not None.") 336 337 self._predictor = predictor 338 self._points_per_side = points_per_side 339 340 # we set the points per batch to 16 for mps for performance reasons 341 # and otherwise keep them at the default of 64 342 if points_per_batch is None: 343 points_per_batch = 16 if util.device_type(predictor.device) == "mps" else 64 344 self._points_per_batch = points_per_batch 345 346 self._crop_n_layers = crop_n_layers 347 self._crop_overlap_ratio = crop_overlap_ratio 348 self._crop_n_points_downscale_factor = crop_n_points_downscale_factor 349 self._stability_score_offset = stability_score_offset
398 @torch.no_grad() 399 def initialize( 400 self, 401 image: np.ndarray, 402 image_embeddings: Optional[util.ImageEmbeddings] = None, 403 i: Optional[int] = None, 404 verbose: bool = False, 405 pbar_init: Optional[callable] = None, 406 pbar_update: Optional[callable] = None, 407 ) -> None: 408 """Initialize image embeddings and masks for an image. 409 410 Args: 411 image: The input image, volume or timeseries. 412 image_embeddings: Optional precomputed image embeddings. 413 See `precompute_image_embeddings` for details. 414 i: Index for the image data. Required if `image` has three spatial dimensions 415 or a time dimension and two spatial dimensions. 416 verbose: Whether to print computation progress. By default, set to 'False'. 417 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 418 Can be used together with pbar_update to handle napari progress bar in other thread. 419 To enable using this function within a threadworker. 420 pbar_update: Callback to update an external progress bar. 421 """ 422 original_size = image.shape[:2] 423 self._original_size = original_size 424 425 crop_boxes, layer_idxs = amg_utils.generate_crop_boxes( 426 original_size, self._crop_n_layers, self._crop_overlap_ratio 427 ) 428 429 # We can set fixed image embeddings if we only have a single crop box (the default setting). 430 # Otherwise we have to recompute the embeddings for each crop and can't precompute. 431 if len(crop_boxes) == 1: 432 if image_embeddings is None: 433 image_embeddings = precompute_image_embeddings(self._predictor, image) 434 set_precomputed(self._predictor, image_embeddings, i=i) 435 precomputed_embeddings = True 436 else: 437 precomputed_embeddings = False 438 439 # we need to cast to the image representation that is compatible with SAM 440 image = util._to_image(image) 441 442 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 443 444 crop_list = [] 445 for crop_box, layer_idx in zip(crop_boxes, layer_idxs): 446 crop_data = self._process_crop( 447 image, crop_box, layer_idx, 448 precomputed_embeddings=precomputed_embeddings, 449 pbar_init=pbar_init, pbar_update=pbar_update, 450 ) 451 crop_list.append(crop_data) 452 pbar_close() 453 454 self._is_initialized = True 455 self._crop_list = crop_list 456 self._crop_boxes = crop_boxes
Initialize image embeddings and masks for an image.
Arguments:
- image: The input image, volume or timeseries.
- image_embeddings: Optional precomputed image embeddings.
See
precompute_image_embeddingsfor details. - i: Index for the image data. Required if
imagehas three spatial dimensions or a time dimension and two spatial dimensions. - verbose: Whether to print computation progress. By default, set to 'False'.
- 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.
458 @torch.no_grad() 459 def generate( 460 self, 461 pred_iou_thresh: float = 0.88, 462 stability_score_thresh: float = 0.95, 463 box_nms_thresh: float = 0.7, 464 crop_nms_thresh: float = 0.7, 465 min_mask_region_area: int = 0, 466 output_mode: str = "instance_segmentation", 467 with_background: bool = True, 468 ) -> Union[List[Dict[str, Any]], np.ndarray]: 469 """Generate instance segmentation for the currently initialized image. 470 471 Args: 472 pred_iou_thresh: Filter threshold in [0, 1], using the mask quality predicted by the model. 473 By default, set to '0.88'. 474 stability_score_thresh: Filter threshold in [0, 1], using the stability of the mask 475 under changes to the cutoff used to binarize the model prediction. By default, set to '0.95'. 476 box_nms_thresh: The IoU threshold used by nonmax suppression to filter duplicate masks. 477 By default, set to '0.7'. 478 crop_nms_thresh: The IoU threshold used by nonmax suppression to filter duplicate masks between crops. 479 By default, set to '0.7'. 480 min_mask_region_area: Minimal size for the predicted masks. By default, set to '0'. 481 output_mode: The form masks are returned in. Possible values are: 482 - 'binary_mask': Return a list of dictionaries with masks encoded as binary masks. 483 - 'coco_rle': Return a list of dictionaries with run-length encoded masks in MS COCO format. 484 - 'instance_segmentation': Return masks merged into an instance segmentation in a single array. 485 - 'rle': Return a list of dictionaries with run-length encoded masks. 486 By default, set to 'instance_segmentation'. 487 with_background: Whether to remove the largest object, which often covers the background. 488 489 Returns: 490 The segmentation masks. 491 """ 492 if not self.is_initialized: 493 raise RuntimeError("AutomaticMaskGenerator has not been initialized. Call initialize first.") 494 495 data = amg_utils.MaskData() 496 for data_, crop_box in zip(self.crop_list, self.crop_boxes): 497 crop_data = self._postprocess_batch( 498 data=deepcopy(data_), 499 crop_box=crop_box, original_size=self.original_size, 500 pred_iou_thresh=pred_iou_thresh, 501 stability_score_thresh=stability_score_thresh, 502 box_nms_thresh=box_nms_thresh 503 ) 504 data.cat(crop_data) 505 506 if len(self.crop_boxes) > 1 and len(data["crop_boxes"]) > 0: 507 # Prefer masks from smaller crops 508 scores = 1 / box_area(data["crop_boxes"]) 509 scores = scores.to(data["boxes"].device) 510 keep_by_nms = batched_nms( 511 data["boxes"].float(), 512 scores, 513 torch.zeros_like(data["boxes"][:, 0]), # categories 514 iou_threshold=crop_nms_thresh, 515 ) 516 data.filter(keep_by_nms) 517 518 data.to_numpy() 519 masks = self._postprocess_masks(data, min_mask_region_area, box_nms_thresh, crop_nms_thresh, output_mode) 520 if output_mode == "instance_segmentation": 521 shape = next(iter(masks))["segmentation"].shape if len(masks) > 0 else self.original_size 522 masks = util.mask_data_to_segmentation( 523 masks, shape=shape, with_background=with_background, merge_exclusively=False 524 ) 525 return masks
Generate instance segmentation for the currently initialized image.
Arguments:
- pred_iou_thresh: Filter threshold in [0, 1], using the mask quality predicted by the model. By default, set to '0.88'.
- stability_score_thresh: Filter threshold in [0, 1], using the stability of the mask under changes to the cutoff used to binarize the model prediction. By default, set to '0.95'.
- box_nms_thresh: The IoU threshold used by nonmax suppression to filter duplicate masks. By default, set to '0.7'.
- crop_nms_thresh: The IoU threshold used by nonmax suppression to filter duplicate masks between crops. By default, set to '0.7'.
- min_mask_region_area: Minimal size for the predicted masks. By default, set to '0'.
- output_mode: The form masks are returned in. Possible values are:
- 'binary_mask': Return a list of dictionaries with masks encoded as binary masks.
- 'coco_rle': Return a list of dictionaries with run-length encoded masks in MS COCO format.
- 'instance_segmentation': Return masks merged into an instance segmentation in a single array.
- 'rle': Return a list of dictionaries with run-length encoded masks. By default, set to 'instance_segmentation'.
- with_background: Whether to remove the largest object, which often covers the background.
Returns:
The segmentation masks.
559class TiledAutomaticMaskGenerator(AutomaticMaskGenerator): 560 """Generates an instance segmentation without prompts, using a point grid. 561 562 Implements the same functionality as `AutomaticMaskGenerator` but for tiled embeddings. 563 564 Args: 565 predictor: The Segment Anything predictor. 566 points_per_side: The number of points to be sampled along one side of the image. 567 If None, `point_grids` must provide explicit point sampling. By default, set to '32'. 568 points_per_batch: The number of points run simultaneously by the model. 569 Higher numbers may be faster but use more GPU memory. By default, set to '64'. 570 point_grids: A list over explicit grids of points used for sampling masks. 571 Normalized to [0, 1] with respect to the image coordinate system. 572 stability_score_offset: The amount to shift the cutoff when calculating the stability score. 573 By default, set to '1.0'. 574 """ 575 576 # We only expose the arguments that make sense for the tiled mask generator. 577 # Anything related to crops doesn't make sense, because we re-use that functionality 578 # for tiling, so these parameters wouldn't have any effect. 579 def __init__( 580 self, 581 predictor: SamPredictor, 582 points_per_side: Optional[int] = 32, 583 points_per_batch: int = 64, 584 point_grids: Optional[List[np.ndarray]] = None, 585 stability_score_offset: float = 1.0, 586 ) -> None: 587 super().__init__( 588 predictor=predictor, 589 points_per_side=points_per_side, 590 points_per_batch=points_per_batch, 591 point_grids=point_grids, 592 stability_score_offset=stability_score_offset, 593 ) 594 595 @torch.no_grad() 596 def initialize( 597 self, 598 image: np.ndarray, 599 image_embeddings: Optional[util.ImageEmbeddings] = None, 600 i: Optional[int] = None, 601 tile_shape: Optional[Tuple[int, int]] = None, 602 halo: Optional[Tuple[int, int]] = None, 603 verbose: bool = False, 604 pbar_init: Optional[callable] = None, 605 pbar_update: Optional[callable] = None, 606 batch_size: int = 1, 607 mask: Optional[np.typing.ArrayLike] = None, 608 ) -> None: 609 """Initialize image embeddings and masks for an image. 610 611 Args: 612 image: The input image, volume or timeseries. 613 image_embeddings: Optional precomputed image embeddings. 614 See `precompute_image_embeddings` for details. 615 i: Index for the image data. Required if `image` has three spatial dimensions 616 or a time dimension and two spatial dimensions. 617 tile_shape: The tile shape for embedding prediction. 618 halo: The overlap of between tiles. 619 verbose: Whether to print computation progress. By default, set to 'False'. 620 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 621 Can be used together with pbar_update to handle napari progress bar in other thread. 622 To enable using this function within a threadworker. 623 pbar_update: Callback to update an external progress bar. 624 batch_size: The batch size for image embedding prediction. By default, set to '1'. 625 mask: An optional mask to define areas that are ignored in the segmentation. 626 """ 627 original_size = image.shape[:2] 628 self._original_size = original_size 629 630 self._image_embeddings, tile_shape, halo, tiles_in_mask = _process_tiled_embeddings( 631 self._predictor, image, image_embeddings, tile_shape, halo, 632 verbose=verbose, batch_size=batch_size, mask=mask, i=i, 633 ) 634 635 tiling = Blocking([0, 0], original_size, tile_shape) 636 if tiles_in_mask is None: 637 n_tiles = tiling.number_of_blocks 638 tile_ids = range(n_tiles) 639 else: 640 n_tiles = len(tiles_in_mask) 641 tile_ids = tiles_in_mask 642 643 # The crop box is always the full local tile. 644 tiles = [tiling.get_block_with_halo(tile_id, list(halo)).outer_block for tile_id in tile_ids] 645 crop_boxes = [[tile.begin[1], tile.begin[0], tile.end[1], tile.end[0]] for tile in tiles] 646 647 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 648 pbar_init(n_tiles, "Compute masks for tile") 649 650 # We need to cast to the image representation that is compatible with SAM. 651 image = util._to_image(image) 652 653 mask_data = [] 654 for idx, tile_id in enumerate(tile_ids): 655 # set the pre-computed embeddings for this tile 656 features = image_embeddings["features"][str(tile_id)] 657 tile_embeddings = { 658 "features": features, 659 "input_size": features.attrs["input_size"], 660 "original_size": features.attrs["original_size"], 661 } 662 set_precomputed(self._predictor, tile_embeddings, i) 663 664 # Compute the mask data for this tile and append it 665 this_mask_data = self._process_crop( 666 image, crop_box=crop_boxes[idx], crop_layer_idx=0, precomputed_embeddings=True 667 ) 668 mask_data.append(this_mask_data) 669 pbar_update(1) 670 pbar_close() 671 672 # set the initialized data 673 self._is_initialized = True 674 self._crop_list = mask_data 675 self._crop_boxes = crop_boxes
Generates an instance segmentation without prompts, using a point grid.
Implements the same functionality as AutomaticMaskGenerator but for tiled embeddings.
Arguments:
- predictor: The Segment Anything predictor.
- points_per_side: The number of points to be sampled along one side of the image.
If None,
point_gridsmust provide explicit point sampling. By default, set to '32'. - points_per_batch: The number of points run simultaneously by the model. Higher numbers may be faster but use more GPU memory. By default, set to '64'.
- point_grids: A list over explicit grids of points used for sampling masks. Normalized to [0, 1] with respect to the image coordinate system.
- stability_score_offset: The amount to shift the cutoff when calculating the stability score. By default, set to '1.0'.
579 def __init__( 580 self, 581 predictor: SamPredictor, 582 points_per_side: Optional[int] = 32, 583 points_per_batch: int = 64, 584 point_grids: Optional[List[np.ndarray]] = None, 585 stability_score_offset: float = 1.0, 586 ) -> None: 587 super().__init__( 588 predictor=predictor, 589 points_per_side=points_per_side, 590 points_per_batch=points_per_batch, 591 point_grids=point_grids, 592 stability_score_offset=stability_score_offset, 593 )
595 @torch.no_grad() 596 def initialize( 597 self, 598 image: np.ndarray, 599 image_embeddings: Optional[util.ImageEmbeddings] = None, 600 i: Optional[int] = None, 601 tile_shape: Optional[Tuple[int, int]] = None, 602 halo: Optional[Tuple[int, int]] = None, 603 verbose: bool = False, 604 pbar_init: Optional[callable] = None, 605 pbar_update: Optional[callable] = None, 606 batch_size: int = 1, 607 mask: Optional[np.typing.ArrayLike] = None, 608 ) -> None: 609 """Initialize image embeddings and masks for an image. 610 611 Args: 612 image: The input image, volume or timeseries. 613 image_embeddings: Optional precomputed image embeddings. 614 See `precompute_image_embeddings` for details. 615 i: Index for the image data. Required if `image` has three spatial dimensions 616 or a time dimension and two spatial dimensions. 617 tile_shape: The tile shape for embedding prediction. 618 halo: The overlap of between tiles. 619 verbose: Whether to print computation progress. By default, set to 'False'. 620 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 621 Can be used together with pbar_update to handle napari progress bar in other thread. 622 To enable using this function within a threadworker. 623 pbar_update: Callback to update an external progress bar. 624 batch_size: The batch size for image embedding prediction. By default, set to '1'. 625 mask: An optional mask to define areas that are ignored in the segmentation. 626 """ 627 original_size = image.shape[:2] 628 self._original_size = original_size 629 630 self._image_embeddings, tile_shape, halo, tiles_in_mask = _process_tiled_embeddings( 631 self._predictor, image, image_embeddings, tile_shape, halo, 632 verbose=verbose, batch_size=batch_size, mask=mask, i=i, 633 ) 634 635 tiling = Blocking([0, 0], original_size, tile_shape) 636 if tiles_in_mask is None: 637 n_tiles = tiling.number_of_blocks 638 tile_ids = range(n_tiles) 639 else: 640 n_tiles = len(tiles_in_mask) 641 tile_ids = tiles_in_mask 642 643 # The crop box is always the full local tile. 644 tiles = [tiling.get_block_with_halo(tile_id, list(halo)).outer_block for tile_id in tile_ids] 645 crop_boxes = [[tile.begin[1], tile.begin[0], tile.end[1], tile.end[0]] for tile in tiles] 646 647 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 648 pbar_init(n_tiles, "Compute masks for tile") 649 650 # We need to cast to the image representation that is compatible with SAM. 651 image = util._to_image(image) 652 653 mask_data = [] 654 for idx, tile_id in enumerate(tile_ids): 655 # set the pre-computed embeddings for this tile 656 features = image_embeddings["features"][str(tile_id)] 657 tile_embeddings = { 658 "features": features, 659 "input_size": features.attrs["input_size"], 660 "original_size": features.attrs["original_size"], 661 } 662 set_precomputed(self._predictor, tile_embeddings, i) 663 664 # Compute the mask data for this tile and append it 665 this_mask_data = self._process_crop( 666 image, crop_box=crop_boxes[idx], crop_layer_idx=0, precomputed_embeddings=True 667 ) 668 mask_data.append(this_mask_data) 669 pbar_update(1) 670 pbar_close() 671 672 # set the initialized data 673 self._is_initialized = True 674 self._crop_list = mask_data 675 self._crop_boxes = crop_boxes
Initialize image embeddings and masks for an image.
Arguments:
- image: The input image, volume or timeseries.
- image_embeddings: Optional precomputed image embeddings.
See
precompute_image_embeddingsfor details. - i: Index for the image data. Required if
imagehas three spatial dimensions or a time dimension and two spatial dimensions. - tile_shape: The tile shape for embedding prediction.
- halo: The overlap of between tiles.
- verbose: Whether to print computation progress. By default, set to 'False'.
- 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.
- batch_size: The batch size for image embedding prediction. By default, set to '1'.
- mask: An optional mask to define areas that are ignored in the segmentation.
683class DecoderAdapter(torch.nn.Module): 684 """Adapter to contain the UNETR decoder in a single module. 685 686 To apply the decoder on top of pre-computed embeddings for the segmentation functionality. 687 See also: https://github.com/constantinpape/torch-em/blob/main/torch_em/model/unetr.py 688 """ 689 def __init__(self, unetr: torch.nn.Module): 690 super().__init__() 691 692 self.base = unetr.base 693 self.out_conv = unetr.out_conv 694 self.deconv_out = unetr.deconv_out 695 self.decoder_head = unetr.decoder_head 696 self.final_activation = unetr.final_activation 697 self.postprocess_masks = unetr.postprocess_masks 698 699 self.decoder = unetr.decoder 700 self.deconv1 = unetr.deconv1 701 self.deconv2 = unetr.deconv2 702 self.deconv3 = unetr.deconv3 703 self.deconv4 = unetr.deconv4 704 705 def _forward_impl(self, input_): 706 z12 = input_ 707 708 z9 = self.deconv1(z12) 709 z6 = self.deconv2(z9) 710 z3 = self.deconv3(z6) 711 z0 = self.deconv4(z3) 712 713 updated_from_encoder = [z9, z6, z3] 714 715 x = self.base(z12) 716 x = self.decoder(x, encoder_inputs=updated_from_encoder) 717 x = self.deconv_out(x) 718 719 x = torch.cat([x, z0], dim=1) 720 x = self.decoder_head(x) 721 722 x = self.out_conv(x) 723 if self.final_activation is not None: 724 x = self.final_activation(x) 725 return x 726 727 def forward(self, input_, input_shape, original_shape): 728 x = self._forward_impl(input_) 729 x = self.postprocess_masks(x, input_shape, original_shape) 730 return x
Adapter to contain the UNETR decoder in a single module.
To apply the decoder on top of pre-computed embeddings for the segmentation functionality. See also: https://github.com/constantinpape/torch-em/blob/main/torch_em/model/unetr.py
689 def __init__(self, unetr: torch.nn.Module): 690 super().__init__() 691 692 self.base = unetr.base 693 self.out_conv = unetr.out_conv 694 self.deconv_out = unetr.deconv_out 695 self.decoder_head = unetr.decoder_head 696 self.final_activation = unetr.final_activation 697 self.postprocess_masks = unetr.postprocess_masks 698 699 self.decoder = unetr.decoder 700 self.deconv1 = unetr.deconv1 701 self.deconv2 = unetr.deconv2 702 self.deconv3 = unetr.deconv3 703 self.deconv4 = unetr.deconv4
Initialize internal Module state, shared by both nn.Module and ScriptModule.
727 def forward(self, input_, input_shape, original_shape): 728 x = self._forward_impl(input_) 729 x = self.postprocess_masks(x, input_shape, original_shape) 730 return x
Define the computation performed at every call.
Should be overridden by all subclasses.
Although the recipe for forward pass needs to be defined within
this function, one should call the Module instance afterwards
instead of this since the former takes care of running the
registered hooks while the latter silently ignores them.
733def get_unetr( 734 image_encoder: torch.nn.Module, 735 decoder_state: Optional[OrderedDict[str, torch.Tensor]] = None, 736 device: Optional[Union[str, torch.device]] = None, 737 out_channels: int = 3, 738 flexible_load_checkpoint: bool = False, 739 final_activation: Optional[str] = "Sigmoid", 740) -> torch.nn.Module: 741 """Get UNETR model for automatic instance segmentation. 742 743 Args: 744 image_encoder: The image encoder of the SAM model. 745 This is used as encoder by the UNETR too. 746 decoder_state: Optional decoder state to initialize the weights of the UNETR decoder. 747 device: The device. By default, automatically chooses the best available device. 748 out_channels: The number of output channels. By default, set to '3'. 749 flexible_load_checkpoint: Whether to allow reinitialization of parameters 750 which could not be found in the provided decoder state. By default, set to 'False'. 751 final_activation: The activation applied to the network output. By default uses a Sigmoid activation. 752 753 Returns: 754 The UNETR model. 755 """ 756 device = util.get_device(device) 757 758 if decoder_state is None: 759 use_conv_transpose = False # By default, we use interpolation for upsampling. 760 else: 761 # From the provided pretrained 'decoder_state', we check whether it uses transposed convolutions. 762 # NOTE: Explanation to the logic below - 763 # - We do this by looking for parameter names that contain '.block.' within the "decoder.samplers" 764 # submodules. This naming convention indicates that transposed convolutions are used, 765 # wrapped inside a custom block module. 766 # - Otherwise '.conv.' appears. It indicates a standard `Conv2d` applied after interpolation for upsampling. 767 use_conv_transpose = any(".block." in k for k in decoder_state.keys() if k.startswith("decoder.samplers")) 768 769 unetr = UNETR( 770 backbone="sam", 771 encoder=image_encoder, 772 out_channels=out_channels, 773 use_sam_stats=True, 774 final_activation=final_activation, 775 use_skip_connection=False, 776 resize_input=True, 777 use_conv_transpose=use_conv_transpose, 778 ) 779 780 if decoder_state is not None: 781 unetr_state_dict = unetr.state_dict() 782 for k, v in unetr_state_dict.items(): 783 if not k.startswith("encoder"): 784 # Whether allow reinitalization of params, if not found or mismatched. 785 if flexible_load_checkpoint: 786 if k in decoder_state: # First check whether the key is available in the provided decoder state. 787 if v.shape != decoder_state[k].shape: # Then check if the sizes mismatch. 788 warnings.warn(f"Shape of '{k}' did not match. Hence, we reinitialize it.") 789 unetr_state_dict[k] = v 790 else: 791 unetr_state_dict[k] = decoder_state[k] 792 else: # Otherwise, allow it to initialize it. 793 warnings.warn(f"Could not find '{k}' in the pretrained state dict. Hence, we reinitialize it.") 794 unetr_state_dict[k] = v 795 796 else: # Be strict on finding the parameter in the decoder state. 797 if k not in decoder_state: 798 raise RuntimeError(f"The parameters for '{k}' could not be found or has a size mismatch.") 799 unetr_state_dict[k] = decoder_state[k] 800 801 unetr.load_state_dict(unetr_state_dict) 802 803 unetr.to(device) 804 return unetr
Get UNETR model for automatic instance segmentation.
Arguments:
- image_encoder: The image encoder of the SAM model. This is used as encoder by the UNETR too.
- decoder_state: Optional decoder state to initialize the weights of the UNETR decoder.
- device: The device. By default, automatically chooses the best available device.
- out_channels: The number of output channels. By default, set to '3'.
- flexible_load_checkpoint: Whether to allow reinitialization of parameters which could not be found in the provided decoder state. By default, set to 'False'.
- final_activation: The activation applied to the network output. By default uses a Sigmoid activation.
Returns:
The UNETR model.
807def get_decoder( 808 image_encoder: torch.nn.Module, 809 decoder_state: OrderedDict[str, torch.Tensor], 810 device: Optional[Union[str, torch.device]] = None, 811) -> DecoderAdapter: 812 """Get decoder to predict outputs for automatic instance segmentation 813 814 Args: 815 image_encoder: The image encoder of the SAM model. 816 decoder_state: State to initialize the weights of the UNETR decoder. 817 device: The device. By default, automatically chooses the best available device. 818 819 Returns: 820 The decoder for instance segmentation. 821 """ 822 unetr = get_unetr(image_encoder, decoder_state, device) 823 return DecoderAdapter(unetr)
Get decoder to predict outputs for automatic instance segmentation
Arguments:
- image_encoder: The image encoder of the SAM model.
- decoder_state: State to initialize the weights of the UNETR decoder.
- device: The device. By default, automatically chooses the best available device.
Returns:
The decoder for instance segmentation.
826def get_predictor_and_decoder( 827 model_type: str, 828 checkpoint_path: Optional[Union[str, os.PathLike]] = None, 829 device: Optional[Union[str, torch.device]] = None, 830 peft_kwargs: Optional[Dict] = None, 831) -> Tuple[SamPredictor, DecoderAdapter]: 832 """Load the SAM model (predictor) and instance segmentation decoder. 833 834 This requires a checkpoint that contains the state for both predictor 835 and decoder. 836 837 Args: 838 model_type: The type of the image encoder used in the SAM model. 839 checkpoint_path: Path to the checkpoint from which to load the data. 840 device: The device. By default, automatically chooses the best available device. 841 peft_kwargs: Keyword arguments for the PEFT wrapper class. 842 843 Returns: 844 The SAM predictor. 845 The decoder for instance segmentation. 846 """ 847 device = util.get_device(device) 848 predictor, state = get_sam_model( 849 model_type=model_type, 850 checkpoint_path=checkpoint_path, 851 device=device, 852 return_state=True, 853 peft_kwargs=peft_kwargs, 854 ) 855 856 if "decoder_state" not in state: 857 raise ValueError( 858 f"The checkpoint at '{checkpoint_path}' or the chosen model '{model_type}' does not contain a decoder state" 859 ) 860 861 decoder = get_decoder(predictor.model.image_encoder, state["decoder_state"], device) 862 return predictor, decoder
Load the SAM model (predictor) and instance segmentation decoder.
This requires a checkpoint that contains the state for both predictor and decoder.
Arguments:
- model_type: The type of the image encoder used in the SAM model.
- checkpoint_path: Path to the checkpoint from which to load the data.
- device: The device. By default, automatically chooses the best available device.
- peft_kwargs: Keyword arguments for the PEFT wrapper class.
Returns:
The SAM predictor. The decoder for instance segmentation.
948class InstanceSegmentationWithDecoder(AutoSegBase): 949 """Generates an instance segmentation without prompts, using a decoder. 950 951 A concrete `AutoSegBase` (like `AutomaticMaskGenerator`), but predicts the segmentation with a 952 decoder instead of grid prompts. 953 954 Use this class as follows: 955 ```python 956 segmenter = InstanceSegmentationWithDecoder(predictor, decoder) 957 segmenter.initialize(image) # Predict the image embeddings and decoder outputs. 958 masks = segmenter.generate(center_distance_threshold=0.75) # Generate the instance segmentation. 959 ``` 960 961 Args: 962 predictor: The segment anything predictor. 963 decoder: The decoder to predict intermediate representations for instance segmentation. 964 """ 965 def __init__(self, predictor: SamPredictor, decoder: torch.nn.Module) -> None: 966 self._predictor = predictor 967 self._decoder = decoder 968 969 # The decoder outputs. 970 self._foreground = None 971 self._center_distances = None 972 self._boundary_distances = None 973 974 self._is_initialized = False 975 976 @torch.no_grad() 977 def initialize( 978 self, 979 image: np.ndarray, 980 image_embeddings: Optional[util.ImageEmbeddings] = None, 981 i: Optional[int] = None, 982 verbose: bool = False, 983 pbar_init: Optional[callable] = None, 984 pbar_update: Optional[callable] = None, 985 ndim: int = 2, 986 ) -> None: 987 """Initialize image embeddings and decoder predictions for an image. 988 989 Args: 990 image: The input image, volume or timeseries. 991 image_embeddings: Optional precomputed image embeddings. 992 See `precompute_image_embeddings` for details. 993 i: Index for the image data. Required if `image` has three spatial dimensions 994 or a time dimension and two spatial dimensions. 995 verbose: Whether to be verbose. By default, set to 'False'. 996 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 997 Can be used together with pbar_update to handle napari progress bar in other thread. 998 To enable using this function within a threadworker. 999 pbar_update: Callback to update an external progress bar. 1000 ndim: The dimensionality of the data. If not given will be deduced from the input data. By default, 2. 1001 """ 1002 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 1003 pbar_init(1, "Initialize instance segmentation with decoder") 1004 1005 if image_embeddings is None: 1006 image_embeddings = precompute_image_embeddings( 1007 predictor=self._predictor, input_=image, ndim=ndim, verbose=verbose 1008 ) 1009 1010 # Get the image embeddings from the predictor. 1011 self._predictor = set_precomputed(self._predictor, image_embeddings, i=i) 1012 embeddings = self._predictor.features 1013 input_shape = tuple(self._predictor.input_size) 1014 original_shape = tuple(self._predictor.original_size) 1015 1016 # Run prediction with the UNETR decoder. 1017 output = self._decoder(embeddings, input_shape, original_shape).cpu().numpy().squeeze(0) 1018 assert output.shape[0] == 3, f"{output.shape}" 1019 pbar_update(1) 1020 pbar_close() 1021 1022 # Set the state. 1023 self._foreground = output[0] 1024 self._center_distances = output[1] 1025 self._boundary_distances = output[2] 1026 self._i = i 1027 self._is_initialized = True 1028 1029 def _to_masks(self, segmentation, output_mode): 1030 if output_mode != "binary_mask": 1031 raise ValueError( 1032 f"Output mode {output_mode} is not supported. Choose one of 'instance_segmentation', 'binary_masks'" 1033 ) 1034 1035 props = regionprops(segmentation) 1036 ndim = segmentation.ndim 1037 assert ndim in (2, 3) 1038 1039 shape = segmentation.shape 1040 if ndim == 2: 1041 crop_box = [0, shape[1], 0, shape[0]] 1042 else: 1043 crop_box = [0, shape[2], 0, shape[1], 0, shape[0]] 1044 1045 # go from skimage bbox in format [y0, x0, y1, x1] to SAM format [x0, w, y0, h] 1046 def to_bbox_2d(bbox): 1047 y0, x0 = bbox[0], bbox[1] 1048 w = bbox[3] - x0 1049 h = bbox[2] - y0 1050 return [x0, w, y0, h] 1051 1052 def to_bbox_3d(bbox): 1053 z0, y0, x0 = bbox[0], bbox[1], bbox[2] 1054 w = bbox[5] - x0 1055 h = bbox[4] - y0 1056 d = bbox[3] - y0 1057 return [x0, w, y0, h, z0, d] 1058 1059 to_bbox = to_bbox_2d if ndim == 2 else to_bbox_3d 1060 masks = [ 1061 { 1062 "segmentation": segmentation == prop.label, 1063 "area": prop.area, 1064 "bbox": to_bbox(prop.bbox), 1065 "crop_box": crop_box, 1066 "seg_id": prop.label, 1067 } for prop in props 1068 ] 1069 return masks 1070 1071 def generate( 1072 self, 1073 center_distance_threshold: float = 0.5, 1074 boundary_distance_threshold: float = 0.5, 1075 foreground_threshold: float = 0.5, 1076 foreground_smoothing: float = 1.0, 1077 distance_smoothing: float = 1.6, 1078 min_size: int = 0, 1079 output_mode: str = "instance_segmentation", 1080 tile_shape: Optional[Tuple[int, int]] = None, 1081 halo: Optional[Tuple[int, int]] = None, 1082 n_threads: Optional[int] = None, 1083 optimize_memory: bool = False, 1084 segmentation: Optional[np.ndarray] = None, 1085 ) -> Union[List[Dict[str, Any]], np.ndarray]: 1086 """Generate instance segmentation for the currently initialized image. 1087 1088 Args: 1089 center_distance_threshold: Center distance predictions below this value will be 1090 used to find seeds (intersected with thresholded boundary distance predictions). 1091 By default, set to '0.5'. 1092 boundary_distance_threshold: Boundary distance predictions below this value will be 1093 used to find seeds (intersected with thresholded center distance predictions). 1094 By default, set to '0.5'. 1095 foreground_threshold: Foreground predictions above this value will be used as foreground mask. 1096 By default, set to '0.5'. 1097 foreground_smoothing: Sigma value for smoothing the foreground predictions, to avoid 1098 checkerboard artifacts in the prediction. By default, set to '1.0'. 1099 distance_smoothing: Sigma value for smoothing the distance predictions. 1100 min_size: Minimal object size in the segmentation result. By default, set to '0'. 1101 output_mode: The form masks are returned in. Possible values are: 1102 - 'binary_mask': Return a list of dictionaries with masks encoded as binary masks. 1103 - 'instance_segmentation': Return masks merged into an instance segmentation in a single array. 1104 By default, set to 'instance_segmentation'. 1105 tile_shape: Tile shape for parallelizing the instance segmentation post-processing. 1106 This parameter is independent from the tile shape for computing the embeddings. 1107 If not given then post-processing will not be parallelized. 1108 halo: Halo for parallel post-processing. See also `tile_shape`. 1109 n_threads: Number of threads for parallel post-processing. See also `tile_shape`. 1110 optimize_memory: Whether to optimize the memory consumption by allocating intermediate files. 1111 segmentation: Optional pre-allocated segmentation. 1112 1113 Returns: 1114 The segmentation masks. 1115 """ 1116 if not self.is_initialized: 1117 raise RuntimeError("InstanceSegmentationWithDecoder has not been initialized. Call initialize first.") 1118 1119 if foreground_smoothing > 0: 1120 foreground = _apply_smoothing(self._foreground, foreground_smoothing, tile_shape, n_threads) 1121 else: 1122 foreground = self._foreground 1123 1124 if tile_shape is None: 1125 segmentation = watershed_from_center_and_boundary_distances( 1126 center_distances=self._center_distances, 1127 boundary_distances=self._boundary_distances, 1128 foreground_map=foreground, 1129 center_distance_threshold=center_distance_threshold, 1130 boundary_distance_threshold=boundary_distance_threshold, 1131 foreground_threshold=foreground_threshold, 1132 distance_smoothing=distance_smoothing, 1133 min_size=min_size, 1134 ) 1135 else: 1136 if halo is None: 1137 raise ValueError("You must pass a value for halo if tile_shape is given.") 1138 1139 # Shards are not thread-safe for parallel writing! So if we have shards we have to use them for tiling. 1140 # This is ok in terms efficiency as GPU tiles are small; shards should still be manegable for the watershed. 1141 if isinstance(segmentation, zarr.Array) and getattr(segmentation, "shards", None) is not None: 1142 tile_shape = segmentation.shards 1143 1144 segmentation = _watershed_from_center_and_boundary_distances_parallel( 1145 center_distances=self._center_distances, 1146 boundary_distances=self._boundary_distances, 1147 foreground_map=foreground, 1148 center_distance_threshold=center_distance_threshold, 1149 boundary_distance_threshold=boundary_distance_threshold, 1150 foreground_threshold=foreground_threshold, 1151 distance_smoothing=distance_smoothing, 1152 min_size=min_size, 1153 tile_shape=tile_shape, 1154 halo=halo, 1155 n_threads=n_threads, 1156 verbose=False, 1157 optimize_memory=optimize_memory, 1158 segmentation=segmentation, 1159 ) 1160 1161 if output_mode != "instance_segmentation": 1162 segmentation = self._to_masks(segmentation, output_mode) 1163 return segmentation 1164 1165 def get_state(self) -> Dict[str, Any]: 1166 """Get the initialized state of the instance segmenter. 1167 1168 Returns: 1169 Instance segmentation state. 1170 """ 1171 if not self.is_initialized: 1172 raise RuntimeError("The state has not been computed yet. Call initialize first.") 1173 1174 return { 1175 "foreground": self._foreground, 1176 "center_distances": self._center_distances, 1177 "boundary_distances": self._boundary_distances, 1178 } 1179 1180 def set_state(self, state: Dict[str, Any]) -> None: 1181 """Set the state of the instance segmenter. 1182 1183 Args: 1184 state: The instance segmentation state 1185 """ 1186 self._foreground = state["foreground"] 1187 self._center_distances = state["center_distances"] 1188 self._boundary_distances = state["boundary_distances"] 1189 self._is_initialized = True 1190 1191 def clear_state(self): 1192 """Clear the state of the instance segmenter. 1193 """ 1194 self._foreground = None 1195 self._center_distances = None 1196 self._boundary_distances = None 1197 self._is_initialized = False
Generates an instance segmentation without prompts, using a decoder.
A concrete AutoSegBase (like AutomaticMaskGenerator), but predicts the segmentation with a
decoder instead of grid prompts.
Use this class as follows:
segmenter = InstanceSegmentationWithDecoder(predictor, decoder)
segmenter.initialize(image) # Predict the image embeddings and decoder outputs.
masks = segmenter.generate(center_distance_threshold=0.75) # Generate the instance segmentation.
Arguments:
- predictor: The segment anything predictor.
- decoder: The decoder to predict intermediate representations for instance segmentation.
965 def __init__(self, predictor: SamPredictor, decoder: torch.nn.Module) -> None: 966 self._predictor = predictor 967 self._decoder = decoder 968 969 # The decoder outputs. 970 self._foreground = None 971 self._center_distances = None 972 self._boundary_distances = None 973 974 self._is_initialized = False
976 @torch.no_grad() 977 def initialize( 978 self, 979 image: np.ndarray, 980 image_embeddings: Optional[util.ImageEmbeddings] = None, 981 i: Optional[int] = None, 982 verbose: bool = False, 983 pbar_init: Optional[callable] = None, 984 pbar_update: Optional[callable] = None, 985 ndim: int = 2, 986 ) -> None: 987 """Initialize image embeddings and decoder predictions for an image. 988 989 Args: 990 image: The input image, volume or timeseries. 991 image_embeddings: Optional precomputed image embeddings. 992 See `precompute_image_embeddings` for details. 993 i: Index for the image data. Required if `image` has three spatial dimensions 994 or a time dimension and two spatial dimensions. 995 verbose: Whether to be verbose. By default, set to 'False'. 996 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 997 Can be used together with pbar_update to handle napari progress bar in other thread. 998 To enable using this function within a threadworker. 999 pbar_update: Callback to update an external progress bar. 1000 ndim: The dimensionality of the data. If not given will be deduced from the input data. By default, 2. 1001 """ 1002 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 1003 pbar_init(1, "Initialize instance segmentation with decoder") 1004 1005 if image_embeddings is None: 1006 image_embeddings = precompute_image_embeddings( 1007 predictor=self._predictor, input_=image, ndim=ndim, verbose=verbose 1008 ) 1009 1010 # Get the image embeddings from the predictor. 1011 self._predictor = set_precomputed(self._predictor, image_embeddings, i=i) 1012 embeddings = self._predictor.features 1013 input_shape = tuple(self._predictor.input_size) 1014 original_shape = tuple(self._predictor.original_size) 1015 1016 # Run prediction with the UNETR decoder. 1017 output = self._decoder(embeddings, input_shape, original_shape).cpu().numpy().squeeze(0) 1018 assert output.shape[0] == 3, f"{output.shape}" 1019 pbar_update(1) 1020 pbar_close() 1021 1022 # Set the state. 1023 self._foreground = output[0] 1024 self._center_distances = output[1] 1025 self._boundary_distances = output[2] 1026 self._i = i 1027 self._is_initialized = True
Initialize image embeddings and decoder predictions for an image.
Arguments:
- image: The input image, volume or timeseries.
- image_embeddings: Optional precomputed image embeddings.
See
precompute_image_embeddingsfor details. - i: Index for the image data. Required if
imagehas three spatial dimensions or a time dimension and two spatial dimensions. - verbose: Whether to be verbose. By default, set to 'False'.
- 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.
- ndim: The dimensionality of the data. If not given will be deduced from the input data. By default, 2.
1071 def generate( 1072 self, 1073 center_distance_threshold: float = 0.5, 1074 boundary_distance_threshold: float = 0.5, 1075 foreground_threshold: float = 0.5, 1076 foreground_smoothing: float = 1.0, 1077 distance_smoothing: float = 1.6, 1078 min_size: int = 0, 1079 output_mode: str = "instance_segmentation", 1080 tile_shape: Optional[Tuple[int, int]] = None, 1081 halo: Optional[Tuple[int, int]] = None, 1082 n_threads: Optional[int] = None, 1083 optimize_memory: bool = False, 1084 segmentation: Optional[np.ndarray] = None, 1085 ) -> Union[List[Dict[str, Any]], np.ndarray]: 1086 """Generate instance segmentation for the currently initialized image. 1087 1088 Args: 1089 center_distance_threshold: Center distance predictions below this value will be 1090 used to find seeds (intersected with thresholded boundary distance predictions). 1091 By default, set to '0.5'. 1092 boundary_distance_threshold: Boundary distance predictions below this value will be 1093 used to find seeds (intersected with thresholded center distance predictions). 1094 By default, set to '0.5'. 1095 foreground_threshold: Foreground predictions above this value will be used as foreground mask. 1096 By default, set to '0.5'. 1097 foreground_smoothing: Sigma value for smoothing the foreground predictions, to avoid 1098 checkerboard artifacts in the prediction. By default, set to '1.0'. 1099 distance_smoothing: Sigma value for smoothing the distance predictions. 1100 min_size: Minimal object size in the segmentation result. By default, set to '0'. 1101 output_mode: The form masks are returned in. Possible values are: 1102 - 'binary_mask': Return a list of dictionaries with masks encoded as binary masks. 1103 - 'instance_segmentation': Return masks merged into an instance segmentation in a single array. 1104 By default, set to 'instance_segmentation'. 1105 tile_shape: Tile shape for parallelizing the instance segmentation post-processing. 1106 This parameter is independent from the tile shape for computing the embeddings. 1107 If not given then post-processing will not be parallelized. 1108 halo: Halo for parallel post-processing. See also `tile_shape`. 1109 n_threads: Number of threads for parallel post-processing. See also `tile_shape`. 1110 optimize_memory: Whether to optimize the memory consumption by allocating intermediate files. 1111 segmentation: Optional pre-allocated segmentation. 1112 1113 Returns: 1114 The segmentation masks. 1115 """ 1116 if not self.is_initialized: 1117 raise RuntimeError("InstanceSegmentationWithDecoder has not been initialized. Call initialize first.") 1118 1119 if foreground_smoothing > 0: 1120 foreground = _apply_smoothing(self._foreground, foreground_smoothing, tile_shape, n_threads) 1121 else: 1122 foreground = self._foreground 1123 1124 if tile_shape is None: 1125 segmentation = watershed_from_center_and_boundary_distances( 1126 center_distances=self._center_distances, 1127 boundary_distances=self._boundary_distances, 1128 foreground_map=foreground, 1129 center_distance_threshold=center_distance_threshold, 1130 boundary_distance_threshold=boundary_distance_threshold, 1131 foreground_threshold=foreground_threshold, 1132 distance_smoothing=distance_smoothing, 1133 min_size=min_size, 1134 ) 1135 else: 1136 if halo is None: 1137 raise ValueError("You must pass a value for halo if tile_shape is given.") 1138 1139 # Shards are not thread-safe for parallel writing! So if we have shards we have to use them for tiling. 1140 # This is ok in terms efficiency as GPU tiles are small; shards should still be manegable for the watershed. 1141 if isinstance(segmentation, zarr.Array) and getattr(segmentation, "shards", None) is not None: 1142 tile_shape = segmentation.shards 1143 1144 segmentation = _watershed_from_center_and_boundary_distances_parallel( 1145 center_distances=self._center_distances, 1146 boundary_distances=self._boundary_distances, 1147 foreground_map=foreground, 1148 center_distance_threshold=center_distance_threshold, 1149 boundary_distance_threshold=boundary_distance_threshold, 1150 foreground_threshold=foreground_threshold, 1151 distance_smoothing=distance_smoothing, 1152 min_size=min_size, 1153 tile_shape=tile_shape, 1154 halo=halo, 1155 n_threads=n_threads, 1156 verbose=False, 1157 optimize_memory=optimize_memory, 1158 segmentation=segmentation, 1159 ) 1160 1161 if output_mode != "instance_segmentation": 1162 segmentation = self._to_masks(segmentation, output_mode) 1163 return segmentation
Generate instance segmentation for the currently initialized image.
Arguments:
- center_distance_threshold: Center distance predictions below this value will be used to find seeds (intersected with thresholded boundary distance predictions). By default, set to '0.5'.
- boundary_distance_threshold: Boundary distance predictions below this value will be used to find seeds (intersected with thresholded center distance predictions). By default, set to '0.5'.
- foreground_threshold: Foreground predictions above this value will be used as foreground mask. By default, set to '0.5'.
- foreground_smoothing: Sigma value for smoothing the foreground predictions, to avoid checkerboard artifacts in the prediction. By default, set to '1.0'.
- distance_smoothing: Sigma value for smoothing the distance predictions.
- min_size: Minimal object size in the segmentation result. By default, set to '0'.
- output_mode: The form masks are returned in. Possible values are:
- 'binary_mask': Return a list of dictionaries with masks encoded as binary masks.
- 'instance_segmentation': Return masks merged into an instance segmentation in a single array. By default, set to 'instance_segmentation'.
- tile_shape: Tile shape for parallelizing the instance segmentation post-processing. This parameter is independent from the tile shape for computing the embeddings. If not given then post-processing will not be parallelized.
- halo: Halo for parallel post-processing. See also
tile_shape. - n_threads: Number of threads for parallel post-processing. See also
tile_shape. - optimize_memory: Whether to optimize the memory consumption by allocating intermediate files.
- segmentation: Optional pre-allocated segmentation.
Returns:
The segmentation masks.
1165 def get_state(self) -> Dict[str, Any]: 1166 """Get the initialized state of the instance segmenter. 1167 1168 Returns: 1169 Instance segmentation state. 1170 """ 1171 if not self.is_initialized: 1172 raise RuntimeError("The state has not been computed yet. Call initialize first.") 1173 1174 return { 1175 "foreground": self._foreground, 1176 "center_distances": self._center_distances, 1177 "boundary_distances": self._boundary_distances, 1178 }
Get the initialized state of the instance segmenter.
Returns:
Instance segmentation state.
1180 def set_state(self, state: Dict[str, Any]) -> None: 1181 """Set the state of the instance segmenter. 1182 1183 Args: 1184 state: The instance segmentation state 1185 """ 1186 self._foreground = state["foreground"] 1187 self._center_distances = state["center_distances"] 1188 self._boundary_distances = state["boundary_distances"] 1189 self._is_initialized = True
Set the state of the instance segmenter.
Arguments:
- state: The instance segmentation state
1191 def clear_state(self): 1192 """Clear the state of the instance segmenter. 1193 """ 1194 self._foreground = None 1195 self._center_distances = None 1196 self._boundary_distances = None 1197 self._is_initialized = False
Clear the state of the instance segmenter.
Inherited Members
1200class TiledInstanceSegmentationWithDecoder(InstanceSegmentationWithDecoder): 1201 """Same as `InstanceSegmentationWithDecoder` but for tiled image embeddings. 1202 """ 1203 1204 # Apply the decoder in a batched fashion, and then perform the resizing independently per output. 1205 # This is necessary, because the individual tiles may have different tile shapes due to border tiles. 1206 def _predict_decoder(self, batched_embeddings, input_shapes, original_shapes): 1207 batched_embeddings = torch.cat(batched_embeddings) 1208 output = self._decoder._forward_impl(batched_embeddings) 1209 1210 batched_output = [] 1211 for x, input_shape, original_shape in zip(output, input_shapes, original_shapes): 1212 x = self._decoder.postprocess_masks(x.unsqueeze(0), input_shape, original_shape).squeeze(0) 1213 batched_output.append(x.cpu().numpy()) 1214 return batched_output 1215 1216 @torch.no_grad() 1217 def initialize( 1218 self, 1219 image: np.ndarray, 1220 image_embeddings: Optional[util.ImageEmbeddings] = None, 1221 i: Optional[int] = None, 1222 tile_shape: Optional[Tuple[int, int]] = None, 1223 halo: Optional[Tuple[int, int]] = None, 1224 verbose: bool = False, 1225 pbar_init: Optional[callable] = None, 1226 pbar_update: Optional[callable] = None, 1227 batch_size: int = 1, 1228 mask: Optional[np.typing.ArrayLike] = None, 1229 ) -> None: 1230 """Initialize image embeddings and decoder predictions for an image. 1231 1232 Args: 1233 image: The input image, volume or timeseries. 1234 image_embeddings: Optional precomputed image embeddings. 1235 See `precompute_image_embeddings` for details. 1236 i: Index for the image data. Required if `image` has three spatial dimensions 1237 or a time dimension and two spatial dimensions. 1238 tile_shape: Shape of the tiles for precomputing image embeddings. 1239 halo: Overlap of the tiles for tiled precomputation of image embeddings. 1240 verbose: Dummy input to be compatible with other function signatures. By default, set to 'False'. 1241 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 1242 Can be used together with pbar_update to handle napari progress bar in other thread. 1243 To enable using this function within a threadworker. 1244 pbar_update: Callback to update an external progress bar. 1245 batch_size: The batch size for image embedding computation and segmentation decoder prediction. 1246 mask: An optional mask to define areas that are ignored in the segmentation. 1247 """ 1248 original_size = image.shape[:2] 1249 self._image_embeddings, tile_shape, halo, tiles_in_mask = _process_tiled_embeddings( 1250 self._predictor, image, image_embeddings, tile_shape, halo, 1251 verbose=verbose, batch_size=batch_size, mask=mask, i=i, 1252 ) 1253 tiling = Blocking([0, 0], original_size, tile_shape) 1254 1255 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 1256 1257 foreground = np.zeros(original_size, dtype="float32") 1258 center_distances = np.zeros(original_size, dtype="float32") 1259 boundary_distances = np.zeros(original_size, dtype="float32") 1260 1261 msg = "Initialize tiled instance segmentation with decoder" 1262 if tiles_in_mask is None: 1263 n_tiles = tiling.number_of_blocks 1264 all_tile_ids = list(range(n_tiles)) 1265 else: 1266 n_tiles = len(tiles_in_mask) 1267 all_tile_ids = tiles_in_mask 1268 msg += " and mask" 1269 1270 n_batches = int(np.ceil(n_tiles / batch_size)) 1271 pbar_init(n_tiles, msg) 1272 tile_ids_for_batches = np.array_split(all_tile_ids, n_batches) 1273 1274 for tile_ids in tile_ids_for_batches: 1275 batched_embeddings, input_shapes, original_shapes = [], [], [] 1276 for tile_id in tile_ids: 1277 # Get the image embeddings from the predictor for this tile. 1278 self._predictor = set_precomputed(self._predictor, self._image_embeddings, i=i, tile_id=tile_id) 1279 1280 batched_embeddings.append(self._predictor.features) 1281 input_shapes.append(tuple(self._predictor.input_size)) 1282 original_shapes.append(tuple(self._predictor.original_size)) 1283 1284 batched_output = self._predict_decoder(batched_embeddings, input_shapes, original_shapes) 1285 1286 for output_id, tile_id in enumerate(tile_ids): 1287 output = batched_output[output_id] 1288 assert output.shape[0] == 3 1289 1290 # Set the predictions in the output for this tile. 1291 block = tiling.get_block_with_halo(tile_id, halo=list(halo)) 1292 local_bb = tuple( 1293 slice(beg, end) for beg, end in zip(block.inner_block_local.begin, block.inner_block_local.end) 1294 ) 1295 inner_bb = tuple(slice(beg, end) for beg, end in zip(block.inner_block.begin, block.inner_block.end)) 1296 1297 foreground[inner_bb] = output[0][local_bb] 1298 center_distances[inner_bb] = output[1][local_bb] 1299 boundary_distances[inner_bb] = output[2][local_bb] 1300 pbar_update(1) 1301 1302 pbar_close() 1303 1304 # Set the state. 1305 self._i = i 1306 self._foreground = foreground 1307 self._center_distances = center_distances 1308 self._boundary_distances = boundary_distances 1309 self._is_initialized = True
Same as InstanceSegmentationWithDecoder but for tiled image embeddings.
1216 @torch.no_grad() 1217 def initialize( 1218 self, 1219 image: np.ndarray, 1220 image_embeddings: Optional[util.ImageEmbeddings] = None, 1221 i: Optional[int] = None, 1222 tile_shape: Optional[Tuple[int, int]] = None, 1223 halo: Optional[Tuple[int, int]] = None, 1224 verbose: bool = False, 1225 pbar_init: Optional[callable] = None, 1226 pbar_update: Optional[callable] = None, 1227 batch_size: int = 1, 1228 mask: Optional[np.typing.ArrayLike] = None, 1229 ) -> None: 1230 """Initialize image embeddings and decoder predictions for an image. 1231 1232 Args: 1233 image: The input image, volume or timeseries. 1234 image_embeddings: Optional precomputed image embeddings. 1235 See `precompute_image_embeddings` for details. 1236 i: Index for the image data. Required if `image` has three spatial dimensions 1237 or a time dimension and two spatial dimensions. 1238 tile_shape: Shape of the tiles for precomputing image embeddings. 1239 halo: Overlap of the tiles for tiled precomputation of image embeddings. 1240 verbose: Dummy input to be compatible with other function signatures. By default, set to 'False'. 1241 pbar_init: Callback to initialize an external progress bar. Must accept number of steps and description. 1242 Can be used together with pbar_update to handle napari progress bar in other thread. 1243 To enable using this function within a threadworker. 1244 pbar_update: Callback to update an external progress bar. 1245 batch_size: The batch size for image embedding computation and segmentation decoder prediction. 1246 mask: An optional mask to define areas that are ignored in the segmentation. 1247 """ 1248 original_size = image.shape[:2] 1249 self._image_embeddings, tile_shape, halo, tiles_in_mask = _process_tiled_embeddings( 1250 self._predictor, image, image_embeddings, tile_shape, halo, 1251 verbose=verbose, batch_size=batch_size, mask=mask, i=i, 1252 ) 1253 tiling = Blocking([0, 0], original_size, tile_shape) 1254 1255 _, pbar_init, pbar_update, pbar_close = util.handle_pbar(verbose, pbar_init, pbar_update) 1256 1257 foreground = np.zeros(original_size, dtype="float32") 1258 center_distances = np.zeros(original_size, dtype="float32") 1259 boundary_distances = np.zeros(original_size, dtype="float32") 1260 1261 msg = "Initialize tiled instance segmentation with decoder" 1262 if tiles_in_mask is None: 1263 n_tiles = tiling.number_of_blocks 1264 all_tile_ids = list(range(n_tiles)) 1265 else: 1266 n_tiles = len(tiles_in_mask) 1267 all_tile_ids = tiles_in_mask 1268 msg += " and mask" 1269 1270 n_batches = int(np.ceil(n_tiles / batch_size)) 1271 pbar_init(n_tiles, msg) 1272 tile_ids_for_batches = np.array_split(all_tile_ids, n_batches) 1273 1274 for tile_ids in tile_ids_for_batches: 1275 batched_embeddings, input_shapes, original_shapes = [], [], [] 1276 for tile_id in tile_ids: 1277 # Get the image embeddings from the predictor for this tile. 1278 self._predictor = set_precomputed(self._predictor, self._image_embeddings, i=i, tile_id=tile_id) 1279 1280 batched_embeddings.append(self._predictor.features) 1281 input_shapes.append(tuple(self._predictor.input_size)) 1282 original_shapes.append(tuple(self._predictor.original_size)) 1283 1284 batched_output = self._predict_decoder(batched_embeddings, input_shapes, original_shapes) 1285 1286 for output_id, tile_id in enumerate(tile_ids): 1287 output = batched_output[output_id] 1288 assert output.shape[0] == 3 1289 1290 # Set the predictions in the output for this tile. 1291 block = tiling.get_block_with_halo(tile_id, halo=list(halo)) 1292 local_bb = tuple( 1293 slice(beg, end) for beg, end in zip(block.inner_block_local.begin, block.inner_block_local.end) 1294 ) 1295 inner_bb = tuple(slice(beg, end) for beg, end in zip(block.inner_block.begin, block.inner_block.end)) 1296 1297 foreground[inner_bb] = output[0][local_bb] 1298 center_distances[inner_bb] = output[1][local_bb] 1299 boundary_distances[inner_bb] = output[2][local_bb] 1300 pbar_update(1) 1301 1302 pbar_close() 1303 1304 # Set the state. 1305 self._i = i 1306 self._foreground = foreground 1307 self._center_distances = center_distances 1308 self._boundary_distances = boundary_distances 1309 self._is_initialized = True
Initialize image embeddings and decoder predictions for an image.
Arguments:
- image: The input image, volume or timeseries.
- image_embeddings: Optional precomputed image embeddings.
See
precompute_image_embeddingsfor details. - i: Index for the image data. Required if
imagehas three spatial dimensions or a time dimension and two spatial dimensions. - tile_shape: Shape of the tiles for precomputing image embeddings.
- halo: Overlap of the tiles for tiled precomputation of image embeddings.
- verbose: Dummy input to be compatible with other function signatures. By default, set to 'False'.
- 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.
- batch_size: The batch size for image embedding computation and segmentation decoder prediction.
- mask: An optional mask to define areas that are ignored in the segmentation.
1393class AutomaticPromptGenerator(InstanceSegmentationWithDecoder): 1394 """Generates an instance segmentation automatically, using automatically generated prompts from a decoder. 1395 1396 This class is used in the same way as `InstanceSegmentationWithDecoder` and `AutomaticMaskGenerator` 1397 1398 Args: 1399 predictor: The segment anything predictor. 1400 decoder: The derive prompts for automatic instance segmentation. 1401 """ 1402 def generate( 1403 self, 1404 min_size: int = 25, 1405 center_distance_threshold: float = 0.5, 1406 boundary_distance_threshold: float = 0.5, 1407 foreground_threshold: float = 0.5, 1408 multimasking: bool = False, 1409 batch_size: int = 32, 1410 nms_threshold: float = 0.9, 1411 intersection_over_min: bool = False, 1412 output_mode: str = "instance_segmentation", 1413 mask_threshold: Optional[Union[float, str]] = None, 1414 refine_with_box_prompts: bool = False, 1415 prompt_function: Optional[callable] = None, 1416 ) -> Union[List[Dict[str, Any]], np.ndarray]: 1417 """Generate the instance segmentation for the currently initialized image. 1418 1419 The instance segmentation is generated by deriving prompts from the foreground and 1420 distance predictions of the segmentation decoder by thresholding these predictions, 1421 intersecting them, computing connected components, and then using the component's 1422 centers as point prompts. The masks are then filtered via NMS and merged into a segmentation. 1423 1424 Args: 1425 min_size: Minimal object size in the segmentation result. By default, set to '25'. 1426 center_distance_threshold: The threshold for the center distance predictions. 1427 boundary_distance_threshold: The threshold for the boundary distance predictions. 1428 multimasking: Whether to use multi-mask prediction for turning the prompts into masks. 1429 batch_size: The batch size for parallelizing the prediction based on prompts. 1430 nms_threshold: The threshold for non-maximum suppression (NMS). 1431 intersection_over_min: Whether to use the minimum area of the two objects or the 1432 intersection over union area (default) in NMS. 1433 output_mode: The form masks are returned in. Possible values are: 1434 - 'binary_mask': Return a list of dictionaries with masks encoded as binary masks. 1435 - 'instance_segmentation': Return masks merged into an instance segmentation in a single array. 1436 By default, set to 'instance_segmentation'. 1437 mask_threshold: The threshold for turning logits into masks in `micro_sam.v1.inference.batched_inference`.` 1438 refine_with_box_prompts: Whether to refine the mask outputs with another round of box promtps 1439 derived from the segmentations after point prompts. 1440 prompt_function: A custom function for deriving prompts from the segmentation decoder predictions. 1441 If given, the default prompt derivation procedure is not used. Must have the following signature: 1442 ``` 1443 def prompt_function(foreground, center_distances, boundary_distances, **kwargs) 1444 ``` 1445 where `foreground`, `center_distances`, and `boundary_distances` are the respective 1446 predictions from the segmentation decoder. It must returns a dictionary containing 1447 either point, box, or mask prompts in a format compatible with 1448 `micro_sam.v1.inference.batched_inference`. 1449 1450 Returns: 1451 The instance segmentation masks. 1452 """ 1453 if not self.is_initialized: 1454 raise RuntimeError("AutomaticPromptGenerator has not been initialized. Call initialize first.") 1455 foreground, center_distances, boundary_distances =\ 1456 self._foreground, self._center_distances, self._boundary_distances 1457 1458 # 1.) Derive promtps from the decoder predictions. 1459 prompt_function = _derive_point_prompts if prompt_function is None else prompt_function 1460 prompts = prompt_function( 1461 foreground=foreground, 1462 center_distances=center_distances, 1463 boundary_distances=boundary_distances, 1464 foreground_threshold=foreground_threshold, 1465 center_distance_threshold=center_distance_threshold, 1466 boundary_distance_threshold=boundary_distance_threshold, 1467 ) 1468 1469 # 2.) Apply the predictor to the prompts. 1470 if prompts is None: # No prompts were derived, we can't do much further and return empty masks. 1471 return np.zeros(foreground.shape, dtype="uint32") if output_mode == "instance_segmentation" else [] 1472 else: 1473 predictions = batched_inference( 1474 self._predictor, 1475 image=None, 1476 batch_size=batch_size, 1477 return_instance_segmentation=False, 1478 multimasking=multimasking, 1479 mask_threshold=mask_threshold, 1480 i=getattr(self, "_i", None), 1481 **prompts, 1482 ) 1483 1484 # 3.) Refine the segmentation with box prompts. 1485 if refine_with_box_prompts: 1486 box_extension = 0.01 # expose as hyperparam? 1487 prompts = _derive_box_prompts(predictions, box_extension) 1488 predictions = batched_inference( 1489 self._predictor, 1490 image=None, 1491 batch_size=batch_size, 1492 return_instance_segmentation=False, 1493 multimasking=multimasking, 1494 mask_threshold=mask_threshold, 1495 i=getattr(self, "_i", None), 1496 **prompts, 1497 ) 1498 1499 # 4.) Apply non-max suppression to the masks. 1500 segmentation = util.apply_nms( 1501 predictions, min_size=min_size, nms_thresh=nms_threshold, intersection_over_min=intersection_over_min, 1502 **APG_MERGE_KWARGS, 1503 ) 1504 if output_mode != "instance_segmentation": 1505 segmentation = self._to_masks(segmentation, output_mode) 1506 return segmentation
Generates an instance segmentation automatically, using automatically generated prompts from a decoder.
This class is used in the same way as InstanceSegmentationWithDecoder and AutomaticMaskGenerator
Arguments:
- predictor: The segment anything predictor.
- decoder: The derive prompts for automatic instance segmentation.
1402 def generate( 1403 self, 1404 min_size: int = 25, 1405 center_distance_threshold: float = 0.5, 1406 boundary_distance_threshold: float = 0.5, 1407 foreground_threshold: float = 0.5, 1408 multimasking: bool = False, 1409 batch_size: int = 32, 1410 nms_threshold: float = 0.9, 1411 intersection_over_min: bool = False, 1412 output_mode: str = "instance_segmentation", 1413 mask_threshold: Optional[Union[float, str]] = None, 1414 refine_with_box_prompts: bool = False, 1415 prompt_function: Optional[callable] = None, 1416 ) -> Union[List[Dict[str, Any]], np.ndarray]: 1417 """Generate the instance segmentation for the currently initialized image. 1418 1419 The instance segmentation is generated by deriving prompts from the foreground and 1420 distance predictions of the segmentation decoder by thresholding these predictions, 1421 intersecting them, computing connected components, and then using the component's 1422 centers as point prompts. The masks are then filtered via NMS and merged into a segmentation. 1423 1424 Args: 1425 min_size: Minimal object size in the segmentation result. By default, set to '25'. 1426 center_distance_threshold: The threshold for the center distance predictions. 1427 boundary_distance_threshold: The threshold for the boundary distance predictions. 1428 multimasking: Whether to use multi-mask prediction for turning the prompts into masks. 1429 batch_size: The batch size for parallelizing the prediction based on prompts. 1430 nms_threshold: The threshold for non-maximum suppression (NMS). 1431 intersection_over_min: Whether to use the minimum area of the two objects or the 1432 intersection over union area (default) in NMS. 1433 output_mode: The form masks are returned in. Possible values are: 1434 - 'binary_mask': Return a list of dictionaries with masks encoded as binary masks. 1435 - 'instance_segmentation': Return masks merged into an instance segmentation in a single array. 1436 By default, set to 'instance_segmentation'. 1437 mask_threshold: The threshold for turning logits into masks in `micro_sam.v1.inference.batched_inference`.` 1438 refine_with_box_prompts: Whether to refine the mask outputs with another round of box promtps 1439 derived from the segmentations after point prompts. 1440 prompt_function: A custom function for deriving prompts from the segmentation decoder predictions. 1441 If given, the default prompt derivation procedure is not used. Must have the following signature: 1442 ``` 1443 def prompt_function(foreground, center_distances, boundary_distances, **kwargs) 1444 ``` 1445 where `foreground`, `center_distances`, and `boundary_distances` are the respective 1446 predictions from the segmentation decoder. It must returns a dictionary containing 1447 either point, box, or mask prompts in a format compatible with 1448 `micro_sam.v1.inference.batched_inference`. 1449 1450 Returns: 1451 The instance segmentation masks. 1452 """ 1453 if not self.is_initialized: 1454 raise RuntimeError("AutomaticPromptGenerator has not been initialized. Call initialize first.") 1455 foreground, center_distances, boundary_distances =\ 1456 self._foreground, self._center_distances, self._boundary_distances 1457 1458 # 1.) Derive promtps from the decoder predictions. 1459 prompt_function = _derive_point_prompts if prompt_function is None else prompt_function 1460 prompts = prompt_function( 1461 foreground=foreground, 1462 center_distances=center_distances, 1463 boundary_distances=boundary_distances, 1464 foreground_threshold=foreground_threshold, 1465 center_distance_threshold=center_distance_threshold, 1466 boundary_distance_threshold=boundary_distance_threshold, 1467 ) 1468 1469 # 2.) Apply the predictor to the prompts. 1470 if prompts is None: # No prompts were derived, we can't do much further and return empty masks. 1471 return np.zeros(foreground.shape, dtype="uint32") if output_mode == "instance_segmentation" else [] 1472 else: 1473 predictions = batched_inference( 1474 self._predictor, 1475 image=None, 1476 batch_size=batch_size, 1477 return_instance_segmentation=False, 1478 multimasking=multimasking, 1479 mask_threshold=mask_threshold, 1480 i=getattr(self, "_i", None), 1481 **prompts, 1482 ) 1483 1484 # 3.) Refine the segmentation with box prompts. 1485 if refine_with_box_prompts: 1486 box_extension = 0.01 # expose as hyperparam? 1487 prompts = _derive_box_prompts(predictions, box_extension) 1488 predictions = batched_inference( 1489 self._predictor, 1490 image=None, 1491 batch_size=batch_size, 1492 return_instance_segmentation=False, 1493 multimasking=multimasking, 1494 mask_threshold=mask_threshold, 1495 i=getattr(self, "_i", None), 1496 **prompts, 1497 ) 1498 1499 # 4.) Apply non-max suppression to the masks. 1500 segmentation = util.apply_nms( 1501 predictions, min_size=min_size, nms_thresh=nms_threshold, intersection_over_min=intersection_over_min, 1502 **APG_MERGE_KWARGS, 1503 ) 1504 if output_mode != "instance_segmentation": 1505 segmentation = self._to_masks(segmentation, output_mode) 1506 return segmentation
Generate the instance segmentation for the currently initialized image.
The instance segmentation is generated by deriving prompts from the foreground and distance predictions of the segmentation decoder by thresholding these predictions, intersecting them, computing connected components, and then using the component's centers as point prompts. The masks are then filtered via NMS and merged into a segmentation.
Arguments:
- min_size: Minimal object size in the segmentation result. By default, set to '25'.
- center_distance_threshold: The threshold for the center distance predictions.
- boundary_distance_threshold: The threshold for the boundary distance predictions.
- multimasking: Whether to use multi-mask prediction for turning the prompts into masks.
- batch_size: The batch size for parallelizing the prediction based on prompts.
- nms_threshold: The threshold for non-maximum suppression (NMS).
- intersection_over_min: Whether to use the minimum area of the two objects or the intersection over union area (default) in NMS.
- output_mode: The form masks are returned in. Possible values are:
- 'binary_mask': Return a list of dictionaries with masks encoded as binary masks.
- 'instance_segmentation': Return masks merged into an instance segmentation in a single array. By default, set to 'instance_segmentation'.
- mask_threshold: The threshold for turning logits into masks in
micro_sam.v1.inference.batched_inference.` - refine_with_box_prompts: Whether to refine the mask outputs with another round of box promtps derived from the segmentations after point prompts.
prompt_function: A custom function for deriving prompts from the segmentation decoder predictions. If given, the default prompt derivation procedure is not used. Must have the following signature:
def prompt_function(foreground, center_distances, boundary_distances, **kwargs)where
foreground,center_distances, andboundary_distancesare the respective predictions from the segmentation decoder. It must returns a dictionary containing either point, box, or mask prompts in a format compatible withmicro_sam.v1.inference.batched_inference.
Returns:
The instance segmentation masks.
1509class TiledAutomaticPromptGenerator(TiledInstanceSegmentationWithDecoder): 1510 """Same as `AutomaticPromptGenerator` but for tiled image embeddings. 1511 """ 1512 def generate( 1513 self, 1514 min_size: int = 25, 1515 center_distance_threshold: float = 0.5, 1516 boundary_distance_threshold: float = 0.5, 1517 foreground_threshold: float = 0.5, 1518 multimasking: bool = False, 1519 batch_size: int = 32, 1520 nms_threshold: float = 0.9, 1521 intersection_over_min: bool = False, 1522 output_mode: str = "instance_segmentation", 1523 mask_threshold: Optional[Union[float, str]] = None, 1524 refine_with_box_prompts: bool = False, 1525 prompt_function: Optional[callable] = None, 1526 optimize_memory: bool = False, 1527 ) -> List[Dict[str, Any]]: 1528 """Generate tiling-based instance segmentation for the currently initialized image. 1529 1530 Args: 1531 min_size: Minimal object size in the segmentation result. By default, set to '25'. 1532 center_distance_threshold: The threshold for the center distance predictions. 1533 boundary_distance_threshold: The threshold for the boundary distance predictions. 1534 multimasking: Whether to use multi-mask prediction for turning the prompts into masks. 1535 batch_size: The batch size for parallelizing the prediction based on prompts. 1536 nms_threshold: The threshold for non-maximum suppression (NMS). 1537 intersection_over_min: Whether to use the minimum area of the two objects or the 1538 intersection over union area (default) in NMS. 1539 output_mode: The form masks are returned in. Possible values are: 1540 - 'binary_mask': Return a list of dictionaries with masks encoded as binary masks. 1541 - 'instance_segmentation': Return masks merged into an instance segmentation in a single array. 1542 By default, set to 'instance_segmentation'. 1543 mask_threshold: The threshold for turining logits into masks in `micro_sam.v1.inference.batched_inference`.` 1544 refine_with_box_prompts: Whether to refine the mask outputs with another round of box promtps 1545 derived from the segmentations after point prompts. Currently not supported for tiled segmentation. 1546 prompt_function: A custom function for deriving prompts from the segmentation decoder predictions. 1547 If given, the default prompt derivation procedure is not used. Must have the following signature: 1548 ``` 1549 def prompt_function(foreground, center_distances, boundary_distances, **kwargs) 1550 ``` 1551 where `foreground`, `center_distances`, and `boundary_distances` are the respective 1552 predictions from the segmentation decoder. It must returns a dictionary containing 1553 either point, box, or mask prompts in a format compatible with 1554 `micro_sam.v1.inference.batched_inference`. 1555 optimize_memory: Whether to optimize the memory consumption by merging the per-slice 1556 segmentation results immediatly with NMS, rather than running a NMS for all results. 1557 This may lead to a slightly different segmentation result and is only compatible with 1558 `refine_with_box_prompts=False` and `output_mode="instance_segmentation"`. 1559 1560 Returns: 1561 The instance segmentation masks. 1562 """ 1563 if not self.is_initialized: 1564 raise RuntimeError("TiledAutomaticPromptGenerator has not been initialized. Call initialize first.") 1565 if optimize_memory and (output_mode != "instance_segmentation" or refine_with_box_prompts): 1566 raise ValueError("Invalid settings") 1567 foreground, center_distances, boundary_distances =\ 1568 self._foreground, self._center_distances, self._boundary_distances 1569 1570 # 1.) Derive promtps from the decoder predictions. 1571 prompt_function = _derive_point_prompts if prompt_function is None else prompt_function 1572 prompts = prompt_function( 1573 foreground, 1574 center_distances, 1575 boundary_distances, 1576 foreground_threshold=foreground_threshold, 1577 center_distance_threshold=center_distance_threshold, 1578 boundary_distance_threshold=boundary_distance_threshold, 1579 ) 1580 1581 # 2.) Apply the predictor to the prompts. 1582 shape = foreground.shape 1583 if prompts is None: # No prompts were derived, we can't do much further and return empty masks. 1584 return np.zeros(shape, dtype="uint32") if output_mode == "instance_segmentation" else [] 1585 else: 1586 if optimize_memory: 1587 prompts.update(dict( 1588 min_size=min_size, nms_thresh=nms_threshold, intersection_over_min=intersection_over_min, 1589 **APG_MERGE_KWARGS, 1590 )) 1591 predictions = batched_tiled_inference( 1592 self._predictor, 1593 image=None, 1594 batch_size=batch_size, 1595 image_embeddings=self._image_embeddings, 1596 return_instance_segmentation=False, 1597 multimasking=multimasking, 1598 optimize_memory=optimize_memory, 1599 i=getattr(self, "_i", None), 1600 **prompts 1601 ) 1602 # Optimize memory directly returns an instance segmentation and does not 1603 # allow for any further refinements. 1604 if optimize_memory: 1605 return predictions 1606 1607 # 3.) Refine the segmentation with box prompts. 1608 if refine_with_box_prompts: 1609 # TODO 1610 raise NotImplementedError 1611 1612 # 4.) Apply non-max suppression to the masks. 1613 segmentation = util.apply_nms( 1614 predictions, shape=shape, min_size=min_size, nms_thresh=nms_threshold, 1615 intersection_over_min=intersection_over_min, **APG_MERGE_KWARGS, 1616 ) 1617 if output_mode != "instance_segmentation": 1618 segmentation = self._to_masks(segmentation, output_mode) 1619 return segmentation 1620 1621 # Set state and get state are not implemented yet, as this generator relies on having the image embeddings 1622 # in the state. However, they should not be serialized here and we have to address this a bit differently. 1623 def get_state(self): 1624 """@private 1625 """ 1626 raise NotImplementedError 1627 1628 def set_state(self, state): 1629 """@private 1630 """ 1631 raise NotImplementedError
Same as AutomaticPromptGenerator but for tiled image embeddings.
1512 def generate( 1513 self, 1514 min_size: int = 25, 1515 center_distance_threshold: float = 0.5, 1516 boundary_distance_threshold: float = 0.5, 1517 foreground_threshold: float = 0.5, 1518 multimasking: bool = False, 1519 batch_size: int = 32, 1520 nms_threshold: float = 0.9, 1521 intersection_over_min: bool = False, 1522 output_mode: str = "instance_segmentation", 1523 mask_threshold: Optional[Union[float, str]] = None, 1524 refine_with_box_prompts: bool = False, 1525 prompt_function: Optional[callable] = None, 1526 optimize_memory: bool = False, 1527 ) -> List[Dict[str, Any]]: 1528 """Generate tiling-based instance segmentation for the currently initialized image. 1529 1530 Args: 1531 min_size: Minimal object size in the segmentation result. By default, set to '25'. 1532 center_distance_threshold: The threshold for the center distance predictions. 1533 boundary_distance_threshold: The threshold for the boundary distance predictions. 1534 multimasking: Whether to use multi-mask prediction for turning the prompts into masks. 1535 batch_size: The batch size for parallelizing the prediction based on prompts. 1536 nms_threshold: The threshold for non-maximum suppression (NMS). 1537 intersection_over_min: Whether to use the minimum area of the two objects or the 1538 intersection over union area (default) in NMS. 1539 output_mode: The form masks are returned in. Possible values are: 1540 - 'binary_mask': Return a list of dictionaries with masks encoded as binary masks. 1541 - 'instance_segmentation': Return masks merged into an instance segmentation in a single array. 1542 By default, set to 'instance_segmentation'. 1543 mask_threshold: The threshold for turining logits into masks in `micro_sam.v1.inference.batched_inference`.` 1544 refine_with_box_prompts: Whether to refine the mask outputs with another round of box promtps 1545 derived from the segmentations after point prompts. Currently not supported for tiled segmentation. 1546 prompt_function: A custom function for deriving prompts from the segmentation decoder predictions. 1547 If given, the default prompt derivation procedure is not used. Must have the following signature: 1548 ``` 1549 def prompt_function(foreground, center_distances, boundary_distances, **kwargs) 1550 ``` 1551 where `foreground`, `center_distances`, and `boundary_distances` are the respective 1552 predictions from the segmentation decoder. It must returns a dictionary containing 1553 either point, box, or mask prompts in a format compatible with 1554 `micro_sam.v1.inference.batched_inference`. 1555 optimize_memory: Whether to optimize the memory consumption by merging the per-slice 1556 segmentation results immediatly with NMS, rather than running a NMS for all results. 1557 This may lead to a slightly different segmentation result and is only compatible with 1558 `refine_with_box_prompts=False` and `output_mode="instance_segmentation"`. 1559 1560 Returns: 1561 The instance segmentation masks. 1562 """ 1563 if not self.is_initialized: 1564 raise RuntimeError("TiledAutomaticPromptGenerator has not been initialized. Call initialize first.") 1565 if optimize_memory and (output_mode != "instance_segmentation" or refine_with_box_prompts): 1566 raise ValueError("Invalid settings") 1567 foreground, center_distances, boundary_distances =\ 1568 self._foreground, self._center_distances, self._boundary_distances 1569 1570 # 1.) Derive promtps from the decoder predictions. 1571 prompt_function = _derive_point_prompts if prompt_function is None else prompt_function 1572 prompts = prompt_function( 1573 foreground, 1574 center_distances, 1575 boundary_distances, 1576 foreground_threshold=foreground_threshold, 1577 center_distance_threshold=center_distance_threshold, 1578 boundary_distance_threshold=boundary_distance_threshold, 1579 ) 1580 1581 # 2.) Apply the predictor to the prompts. 1582 shape = foreground.shape 1583 if prompts is None: # No prompts were derived, we can't do much further and return empty masks. 1584 return np.zeros(shape, dtype="uint32") if output_mode == "instance_segmentation" else [] 1585 else: 1586 if optimize_memory: 1587 prompts.update(dict( 1588 min_size=min_size, nms_thresh=nms_threshold, intersection_over_min=intersection_over_min, 1589 **APG_MERGE_KWARGS, 1590 )) 1591 predictions = batched_tiled_inference( 1592 self._predictor, 1593 image=None, 1594 batch_size=batch_size, 1595 image_embeddings=self._image_embeddings, 1596 return_instance_segmentation=False, 1597 multimasking=multimasking, 1598 optimize_memory=optimize_memory, 1599 i=getattr(self, "_i", None), 1600 **prompts 1601 ) 1602 # Optimize memory directly returns an instance segmentation and does not 1603 # allow for any further refinements. 1604 if optimize_memory: 1605 return predictions 1606 1607 # 3.) Refine the segmentation with box prompts. 1608 if refine_with_box_prompts: 1609 # TODO 1610 raise NotImplementedError 1611 1612 # 4.) Apply non-max suppression to the masks. 1613 segmentation = util.apply_nms( 1614 predictions, shape=shape, min_size=min_size, nms_thresh=nms_threshold, 1615 intersection_over_min=intersection_over_min, **APG_MERGE_KWARGS, 1616 ) 1617 if output_mode != "instance_segmentation": 1618 segmentation = self._to_masks(segmentation, output_mode) 1619 return segmentation
Generate tiling-based instance segmentation for the currently initialized image.
Arguments:
- min_size: Minimal object size in the segmentation result. By default, set to '25'.
- center_distance_threshold: The threshold for the center distance predictions.
- boundary_distance_threshold: The threshold for the boundary distance predictions.
- multimasking: Whether to use multi-mask prediction for turning the prompts into masks.
- batch_size: The batch size for parallelizing the prediction based on prompts.
- nms_threshold: The threshold for non-maximum suppression (NMS).
- intersection_over_min: Whether to use the minimum area of the two objects or the intersection over union area (default) in NMS.
- output_mode: The form masks are returned in. Possible values are:
- 'binary_mask': Return a list of dictionaries with masks encoded as binary masks.
- 'instance_segmentation': Return masks merged into an instance segmentation in a single array. By default, set to 'instance_segmentation'.
- mask_threshold: The threshold for turining logits into masks in
micro_sam.v1.inference.batched_inference.` - refine_with_box_prompts: Whether to refine the mask outputs with another round of box promtps derived from the segmentations after point prompts. Currently not supported for tiled segmentation.
prompt_function: A custom function for deriving prompts from the segmentation decoder predictions. If given, the default prompt derivation procedure is not used. Must have the following signature:
def prompt_function(foreground, center_distances, boundary_distances, **kwargs)where
foreground,center_distances, andboundary_distancesare the respective predictions from the segmentation decoder. It must returns a dictionary containing either point, box, or mask prompts in a format compatible withmicro_sam.v1.inference.batched_inference.- optimize_memory: Whether to optimize the memory consumption by merging the per-slice
segmentation results immediatly with NMS, rather than running a NMS for all results.
This may lead to a slightly different segmentation result and is only compatible with
refine_with_box_prompts=Falseandoutput_mode="instance_segmentation".
Returns:
The instance segmentation masks.
1634def get_instance_segmentation_generator( 1635 predictor: SamPredictor, 1636 is_tiled: bool, 1637 decoder: Optional[torch.nn.Module] = None, 1638 segmentation_mode: Optional[Literal["amg", "ais", "apg"]] = None, 1639 **kwargs, 1640) -> AutoSegBase: 1641 f"""Get the automatic mask generator. 1642 1643 Args: 1644 predictor: The segment anything predictor. 1645 is_tiled: Whether tiled embeddings are used. 1646 decoder: Decoder to predict instacne segmmentation. 1647 segmentation_mode: The segmentation mode. One of 'amg', 'ais', or 'apg'. 1648 By default, '{DEFAULT_SEGMENTATION_MODE_WITH_DECODER}' is used if a decoder is passed, 1649 otherwise 'amg' is used. 1650 kwargs: The keyword arguments of the segmentation genetator class. 1651 1652 Returns: 1653 The segmentation generator instance. 1654 """ 1655 # Choose the segmentation decoder default depending on whether we have a decoder. 1656 if segmentation_mode is None: 1657 segmentation_mode = "amg" if decoder is None else DEFAULT_SEGMENTATION_MODE_WITH_DECODER 1658 1659 if segmentation_mode.lower() == "amg": 1660 segmenter_class = TiledAutomaticMaskGenerator if is_tiled else AutomaticMaskGenerator 1661 segmenter = segmenter_class(predictor, **kwargs) 1662 elif segmentation_mode.lower() == "ais": 1663 assert decoder is not None 1664 segmenter_class = TiledInstanceSegmentationWithDecoder if is_tiled else InstanceSegmentationWithDecoder 1665 segmenter = segmenter_class(predictor, decoder, **kwargs) 1666 elif segmentation_mode.lower() == "apg": 1667 assert decoder is not None 1668 segmenter_class = TiledAutomaticPromptGenerator if is_tiled else AutomaticPromptGenerator 1669 segmenter = segmenter_class(predictor, decoder, **kwargs) 1670 else: 1671 raise ValueError(f"Invalid segmentation_mode: {segmentation_mode}. Choose one of 'amg', 'ais', or 'apg'.") 1672 1673 return segmenter