micro_sam.v1.inference
1import gc 2import os 3from typing import Any, Dict, List, Optional, Union, Tuple 4 5import numpy as np 6 7from segment_anything import SamPredictor 8import segment_anything.utils.amg as amg_utils 9from segment_anything.utils.transforms import ResizeLongestSide 10 11import torch 12import torch.nn.functional as F 13 14try: 15 from napari.utils import progress as tqdm 16except ImportError: 17 from tqdm import tqdm 18 19from bioimage_cpp.utils import Blocking, segmentation_overlap 20 21from .. import util 22from .._vendored import batched_mask_to_box 23from .util import precompute_image_embeddings, set_precomputed 24 25 26def _validate_inputs( 27 boxes, points, point_labels, multimasking, return_instance_segmentation, segmentation_ids, logits_masks 28): 29 if multimasking and (segmentation_ids is not None) and (not return_instance_segmentation): 30 raise NotImplementedError 31 32 if (points is None) != (point_labels is None): 33 raise ValueError( 34 "If you have point prompts both `points` and `point_labels` have to be passed, " 35 "but you passed only one of them." 36 ) 37 38 have_points = points is not None 39 have_boxes = boxes is not None 40 have_logits = logits_masks is not None 41 if (not have_points) and (not have_boxes): 42 raise ValueError("Point and/or box prompts have to be passed, you passed neither.") 43 44 if have_points and (len(point_labels) != len(points)): 45 raise ValueError( 46 f"The number of point coordinates and labels does not match: {len(point_labels)} != {len(points)}" 47 ) 48 49 if (have_points and have_boxes) and (len(points) != len(boxes)): 50 raise ValueError( 51 f"The number of point and box prompts does not match: {len(points)} != {len(boxes)}" 52 ) 53 54 if have_logits: 55 if have_points and (len(logits_masks) != len(point_labels)): 56 raise ValueError( 57 f"The number of point and logits does not match: {len(points) != len(logits_masks)}" 58 ) 59 elif have_boxes and (len(logits_masks) != len(boxes)): 60 raise ValueError( 61 f"The number of boxes and logits does not match: {len(boxes)} != {len(logits_masks)}" 62 ) 63 64 n_prompts = boxes.shape[0] if have_boxes else points.shape[0] 65 66 if (segmentation_ids is not None) and (len(segmentation_ids) != n_prompts): 67 raise ValueError( 68 f"The number of segmentation ids and prompts does not match: {len(segmentation_ids)} != {n_prompts}" 69 ) 70 71 return n_prompts, have_boxes, have_points, have_logits 72 73 74def _local_otsu_threshold(images: torch.Tensor, window_size: int = 31, num_bins: int = 64, eps: float = 1e-6): 75 x = images 76 B, _, H, W = x.shape 77 device = x.device 78 79 # Work in float32 for stability even if input is fp16 80 x = x.to(torch.float32) 81 82 # per-image min/max for normalization to [0, 1] 83 x_flat = x.view(B, -1) 84 x_min = x_flat.min(dim=1).values.view(B, 1, 1, 1) 85 x_max = x_flat.max(dim=1).values.view(B, 1, 1, 1) 86 x_range = (x_max - x_min).clamp_min(eps) 87 88 x_norm = (x - x_min) / x_range # (B,1,H,W), in [0,1] 89 90 # extract local patches via unfold 91 pad = window_size // 2 92 patches = F.unfold(x_norm, kernel_size=window_size, padding=pad) # (B, P, L) 93 # P = window_size * window_size, L = H * W 94 B_, P, L = patches.shape 95 96 # quantize to bins 97 bin_idx = (patches * (num_bins - 1)).long().clamp(0, num_bins - 1) # (B, P, L) 98 99 # build histograms per patch 100 # one_hot: (B, L, num_bins) 101 one_hot = torch.zeros(B, L, num_bins, device=device, dtype=torch.float32) 102 idx = bin_idx.transpose(1, 2) # (B, L, P) 103 src = torch.ones_like(idx, dtype=one_hot.dtype) # (B, L, P) 104 one_hot.scatter_add_(2, idx, src) 105 # hist: (B, num_bins, L) 106 hist = one_hot.permute(0, 2, 1) 107 108 # Otsu per patch (vectorized) 109 # p: (B, bins, L) 110 p = hist / hist.sum(dim=1, keepdim=True).clamp_min(eps) 111 112 bins = torch.arange(num_bins, device=device, dtype=torch.float32).view(1, num_bins, 1) 113 114 omega1 = torch.cumsum(p, dim=1) # (B, bins, L) 115 mu = torch.cumsum(p * bins, dim=1) # (B, bins, L) 116 mu_T = mu[:, -1:, :] # (B, 1, L) 117 118 omega2 = 1.0 - omega1 119 120 mu1 = mu / omega1.clamp_min(eps) 121 mu2 = (mu_T - mu) / omega2.clamp_min(eps) 122 123 sigma_b2 = omega1 * omega2 * (mu1 - mu2) ** 2 # (B, bins, L) 124 125 # argmax over bins gives local threshold bin per patch 126 t_bin = torch.argmax(sigma_b2, dim=1) # (B, L) 127 t_norm = t_bin.to(torch.float32) / (num_bins - 1) # normalized [0,1] 128 129 # map thresholds back to original intensity scale (per-image) 130 # x_min, x_range: (B,1,1,1) -> flatten batch dims 131 thr_vals = x_min.view(B, 1) + t_norm * x_range.view(B, 1) # (B, L) 132 # clamp to >= 0 because foreground is positive 133 thr_vals = thr_vals.clamp_min(0.0) 134 135 thresholds = thr_vals.view(B, H, W) 136 # Take the spatial max over the thresholds. 137 thresholds = torch.amax(thresholds, dim=(1, 2), keepdims=True) 138 return thresholds 139 140 141def _process_masks_for_batch(batch_masks, batch_ious, batch_logits, return_highres_logits, mask_threshold): 142 batch_data = amg_utils.MaskData(masks=batch_masks.flatten(0, 1), iou_preds=batch_ious.flatten(0, 1)) 143 batch_data["logits"] = batch_masks.clone() if return_highres_logits else batch_logits 144 # TODO: probably the best heuristic: choose the lowest threshold which still has stable masks. 145 # To do this: go through the thresholds, starting from 0 in smallish increments, compute stability score, 146 # select the threshold before the stability score starts to drop. 147 if mask_threshold == "auto": 148 thresholds = _local_otsu_threshold(batch_logits) 149 batch_data["stability_scores"] = amg_utils.calculate_stability_score(batch_data["masks"], thresholds, 1.0) 150 batch_data["masks"] = (batch_data["masks"] > thresholds).type(torch.bool) 151 else: 152 batch_data["stability_scores"] = amg_utils.calculate_stability_score(batch_data["masks"], mask_threshold, 1.0) 153 batch_data["masks"] = (batch_data["masks"] > mask_threshold).type(torch.bool) 154 batch_data["boxes"] = batched_mask_to_box(batch_data["masks"]) 155 return batch_data 156 157 158@torch.no_grad() 159def batched_inference( 160 predictor: SamPredictor, 161 image: Optional[np.ndarray], 162 batch_size: int, 163 boxes: Optional[np.ndarray] = None, 164 points: Optional[np.ndarray] = None, 165 point_labels: Optional[np.ndarray] = None, 166 multimasking: bool = False, 167 embedding_path: Optional[Union[str, os.PathLike]] = None, 168 return_instance_segmentation: bool = True, 169 segmentation_ids: Optional[list] = None, 170 reduce_multimasking: bool = True, 171 logits_masks: Optional[torch.Tensor] = None, 172 verbose_embeddings: bool = True, 173 mask_threshold: Optional[Union[float, str]] = None, 174 return_highres_logits: bool = False, 175 i: Optional[int] = None, 176) -> Union[List[List[Dict[str, Any]]], np.ndarray]: 177 """Run batched inference for input prompts. 178 179 Args: 180 predictor: The Segment Anything predictor. 181 image: The input image. If None, we assume that the image embeddings have already been computed. 182 batch_size: The batch size to use for inference. 183 boxes: The box prompts. Array of shape N_PROMPTS x 4. 184 The bounding boxes are represented by [MIN_X, MIN_Y, MAX_X, MAX_Y]. 185 points: The point prompt coordinates. Array of shape N_PROMPTS x 1 x 2. 186 The points are represented by their coordinates [X, Y], which are given in the last dimension. 187 point_labels: The point prompt labels. Array of shape N_PROMPTS x 1. 188 The labels are either 0 (negative prompt) or 1 (positive prompt). 189 multimasking: Whether to predict with 3 or 1 mask. By default, set to 'False'. 190 embedding_path: Cache path for the image embeddings. By default, computed on-the-fly. 191 return_instance_segmentation: Whether to return a instance segmentation 192 or the individual mask data. By default, set to 'True'. 193 segmentation_ids: Fixed segmentation ids to assign to the masks 194 derived from the prompts. 195 reduce_multimasking: Whether to choose the most likely masks with 196 highest ious from multimasking. By default, set to 'True'. 197 logits_masks: The logits masks. Array of shape N_PROMPTS x 1 x 256 x 256. 198 Whether to use the logits masks from previous segmentation. 199 verbose_embeddings: Whether to show progress outputs of computing image embeddings. 200 By default, set to 'True'. 201 mask_threshold: The theshold for binarizing masks based on the predicted values. 202 If None, the default threshold 0 is used. If "auto" is passed then the threshold is 203 determined with a local otsu filter. 204 return_highres_logits: Wheher to return high-resolution logits. 205 i: Index for the image data. Required if `image` has three spatial dimensions 206 or a time dimension and two spatial dimensions. 207 208 Returns: 209 The predicted segmentation masks. 210 """ 211 n_prompts, have_boxes, have_points, have_logits = _validate_inputs( 212 boxes, points, point_labels, multimasking, return_instance_segmentation, segmentation_ids, logits_masks 213 ) 214 215 # Compute the image embeddings. 216 if image is None: # This means the image embeddings are computed already. 217 # Call get image embeddings, this will throw an error if they have not yet been computed. 218 predictor.get_image_embedding() 219 else: 220 input_ = image if i is None else image[i] 221 # The input is always one 2d image. Deducing the dimensionality would read an RGB image as a volume. 222 image_embeddings = precompute_image_embeddings( 223 predictor, input_, embedding_path, ndim=2, verbose=verbose_embeddings 224 ) 225 set_precomputed(predictor, image_embeddings) 226 227 # Determine the number of batches. 228 n_batches = int(np.ceil(float(n_prompts) / batch_size)) 229 230 # Preprocess the prompts. 231 device = predictor.device 232 transform_function = ResizeLongestSide(1024) 233 image_shape = predictor.original_size 234 if have_boxes: 235 boxes = transform_function.apply_boxes(boxes, image_shape) 236 boxes = torch.tensor(boxes, dtype=torch.float32).to(device) 237 if have_points: 238 points = transform_function.apply_coords(points, image_shape) 239 points = torch.tensor(points, dtype=torch.float32).to(device) 240 point_labels = torch.tensor(point_labels, dtype=torch.float32).to(device) 241 242 masks = amg_utils.MaskData() 243 mask_threshold = predictor.model.mask_threshold if mask_threshold is None else mask_threshold 244 for batch_idx in range(n_batches): 245 batch_start = batch_idx * batch_size 246 batch_stop = min((batch_idx + 1) * batch_size, n_prompts) 247 248 batch_boxes = boxes[batch_start:batch_stop] if have_boxes else None 249 batch_points = points[batch_start:batch_stop] if have_points else None 250 batch_labels = point_labels[batch_start:batch_stop] if have_points else None 251 batch_logits = logits_masks[batch_start:batch_stop] if have_logits else None 252 253 batch_masks, batch_ious, batch_logits = predictor.predict_torch( 254 point_coords=batch_points, 255 point_labels=batch_labels, 256 boxes=batch_boxes, 257 mask_input=batch_logits, 258 multimask_output=multimasking, 259 return_logits=True, 260 ) 261 262 # If we expect to reduce the masks from multimasking and use multi-masking, 263 # then we need to select the most likely mask (according to the predicted IOU) here. 264 if reduce_multimasking and multimasking: 265 _, max_index = batch_ious.max(axis=1) 266 batch_masks = torch.cat([batch_masks[i, max_id][None] for i, max_id in enumerate(max_index)]).unsqueeze(1) 267 batch_ious = torch.cat([batch_ious[i, max_id][None] for i, max_id in enumerate(max_index)]).unsqueeze(1) 268 batch_logits = torch.cat([batch_logits[i, max_id][None] for i, max_id in enumerate(max_index)]).unsqueeze(1) 269 270 batch_data = _process_masks_for_batch( 271 batch_masks, batch_ious, batch_logits, return_highres_logits, mask_threshold 272 ) 273 masks.cat(batch_data) 274 275 # Mask data to records. 276 masks = [ 277 { 278 "segmentation": masks["masks"][idx], 279 "area": masks["masks"][idx].sum(), 280 "bbox": amg_utils.box_xyxy_to_xywh(masks["boxes"][idx]).tolist(), 281 "predicted_iou": masks["iou_preds"][idx].item(), 282 "stability_score": masks["stability_scores"][idx].item(), 283 "seg_id": idx + 1 if segmentation_ids is None else int(segmentation_ids[idx]), 284 "logits": masks["logits"][idx] 285 } 286 for idx in range(len(masks["masks"])) 287 ] 288 289 if return_instance_segmentation: 290 masks = util.mask_data_to_segmentation(masks, min_object_size=0) 291 return masks 292 293 294def _require_tiled_embeddings( 295 predictor, image, image_embeddings, embedding_path, tile_shape, halo, verbose_embeddings 296): 297 if image_embeddings is None: 298 assert image is not None 299 assert (tile_shape is not None) and (halo is not None) 300 shape = image.shape[:2] 301 image_embeddings = precompute_image_embeddings( 302 predictor, image, embedding_path, ndim=2, tile_shape=tile_shape, halo=halo, verbose=verbose_embeddings 303 ) 304 else: # This means the image embeddings are computed already. 305 attrs = image_embeddings["features"].attrs 306 tile_shape_, halo_ = attrs["tile_shape"], attrs["halo"] 307 shape = attrs["shape"] 308 if tile_shape is None: 309 tile_shape = tile_shape_ 310 elif any(ts != ts_ for ts, ts_ in zip(tile_shape, tile_shape_)): 311 raise ValueError(f"Incompatible tile shapes: {tile_shape} != {tile_shape_}") 312 if halo is None: 313 halo = halo_ 314 elif any(ts != ts_ for ts, ts_ in zip(halo, halo_)): 315 raise ValueError(f"Incompatible tile shapes: {halo} != {halo_}") 316 317 return image_embeddings, shape, tile_shape, halo 318 319 320def _merge_segmentations(this_seg, prev_seg, overlap_threshold=0.75): 321 # Discard new ids with too much overlap. 322 ovlp = segmentation_overlap(this_seg, prev_seg) 323 ids = np.unique(this_seg) 324 if ids[0] == 0: 325 ids = ids[1:] 326 discard_ids = [] 327 for seg_id in ids: 328 ovlp_table = ovlp.overlaps_for_label_a(seg_id, normalize=True) 329 ovlp_ids, ovlp_vals = ovlp_table["label"], ovlp_table["fraction"] 330 ovlp_vals = ovlp_vals[ovlp_ids != 0] 331 if ovlp_vals.size > 0 and ovlp_vals[0] > overlap_threshold: 332 discard_ids.append(seg_id) 333 334 # Make sure the previous segmentation is fully preserved. 335 captured = prev_seg != 0 336 this_seg[captured] = prev_seg[captured] 337 return this_seg 338 339 340# Note: we merge with a very simple first come first serve strategy. 341# This could also be improved by merging according to IoUs. 342# (But would add a lot of complexity) 343def _stitch_segmentation(masks, tile_ids, tiling, halo, output_shape, verbose=False): 344 assert len(masks) == len(tile_ids), f"{len(masks)}, {len(tile_ids)}" 345 segmentation = np.zeros(output_shape, dtype="uint32") 346 347 for tile_id, this_seg in util._progress_bar(zip(tile_ids, masks), desc="Stitch tiles", disable=not verbose): 348 tile = tiling.getBlockWithHalo(tile_id, list(halo)).outerBlock 349 bb = tuple(slice(begin, end) for begin, end in zip(tile.begin, tile.end)) 350 if tile_id == 0: 351 segmentation[bb] = this_seg 352 else: 353 # Merge the segmentation, discarding ids with too much overlap. 354 prev_seg = segmentation[bb] 355 assert prev_seg.shape == this_seg.shape, f"{tile_id}: {prev_seg.shape}, {this_seg.shape}" 356 this_seg = _merge_segmentations(this_seg, prev_seg) 357 segmentation[bb] = this_seg 358 359 return segmentation 360 361 362@torch.no_grad() 363def batched_tiled_inference( 364 predictor: SamPredictor, 365 image: Optional[np.ndarray], 366 batch_size: int, 367 image_embeddings: Optional[util.ImageEmbeddings] = None, 368 boxes: Optional[np.ndarray] = None, 369 points: Optional[np.ndarray] = None, 370 point_labels: Optional[np.ndarray] = None, 371 multimasking: bool = False, 372 embedding_path: Optional[Union[str, os.PathLike]] = None, 373 return_instance_segmentation: bool = True, 374 reduce_multimasking: bool = True, 375 logits_masks: Optional[torch.Tensor] = None, 376 verbose_embeddings: bool = True, 377 mask_threshold: Optional[Union[float, str]] = None, 378 tile_shape: Optional[Tuple[int, int]] = None, 379 halo: Optional[Tuple[int, int]] = None, 380 optimize_memory: bool = False, 381 i: Optional[int] = None, 382 **nms_kwargs, 383) -> Union[List[List[Dict[str, Any]]], np.ndarray]: 384 """Run batched inference for input prompts. 385 386 Args: 387 predictor: The Segment Anything predictor. 388 image: The input image. If None, we assume that the image embeddings have already been computed. 389 batch_size: The batch size to use for inference. 390 boxes: The box prompts. Array of shape N_PROMPTS x 4. 391 The bounding boxes are represented by [MIN_X, MIN_Y, MAX_X, MAX_Y]. 392 points: The point prompt coordinates. Array of shape N_PROMPTS x 1 x 2. 393 The points are represented by their coordinates [X, Y], which are given in the last dimension. 394 point_labels: The point prompt labels. Array of shape N_PROMPTS x 1. 395 The labels are either 0 (negative prompt) or 1 (positive prompt). 396 multimasking: Whether to predict with 3 or 1 mask. By default, set to 'False'. 397 embedding_path: Cache path for the image embeddings. By default, computed on-the-fly. 398 return_instance_segmentation: Whether to return a instance segmentation 399 or the individual mask data. By default, set to 'True'. 400 segmentation_ids: Fixed segmentation ids to assign to the masks 401 derived from the prompts. 402 reduce_multimasking: Whether to choose the most likely masks with 403 highest ious from multimasking. By default, set to 'True'. 404 logits_masks: The logits masks. Array of shape N_PROMPTS x 1 x 256 x 256. 405 Whether to use the logits masks from previous segmentation. 406 verbose_embeddings: Whether to show progress outputs of computing image embeddings. 407 By default, set to 'True'. 408 mask_threshold: The theshold for binarizing masks based on the predicted values. 409 If None, the default threshold 0 is used. If "auto" is passed then the threshold is 410 determined with a local otsu filter. 411 tile_shape: The tile shape for embedding prediction. 412 halo: The overlap of between tiles. 413 optimize_memory: Whether to optimize the memory usage. If set to True: 414 - NMS will be applied directly for each tile to reduce it to a per-tile instance segmentation. 415 - The per-tile segmentations will be stitched. 416 - The result will be returned as an instance segmentation. 417 i: Index for the image data. Required if `image` has three spatial dimensions 418 or a time dimension and two spatial dimensions. 419 nms_kwargs: Keyword arguments for the NMS operations that is used for optimize_memory=True. 420 Does not have any effect for optimize_memory=False. 421 422 Returns: 423 The predicted segmentation masks. 424 """ 425 # Validate inputs and get input prompt summary. 426 segmentation_ids = None 427 n_prompts, have_boxes, have_points, have_logits = _validate_inputs( 428 boxes, points, point_labels, multimasking, return_instance_segmentation, segmentation_ids, logits_masks 429 ) 430 if have_logits: 431 raise NotImplementedError 432 433 # Get the tiling parameters and compute embeddings if needed. 434 image_embeddings, shape, tile_shape, halo = _require_tiled_embeddings( 435 predictor, image, image_embeddings, embedding_path, tile_shape, halo, verbose_embeddings 436 ) 437 438 # Order the prompts by tile and then iterate over the tiles. 439 tiling = Blocking([0, 0], shape, tile_shape) 440 box_to_tile, point_to_tile, label_to_tile, logits_to_tile = {}, {}, {}, {} 441 tile_ids = [] 442 443 # Box prompts are in the format N x 4. Boxes are stored in order [MIN_X, MIN_Y, MAX_X, MAX_Y]. 444 # Points are in the Format N x 1 x 2 with coordinate order X, Y. 445 # Point labels are in the format N x 1. 446 # Mask prompts are in the format N x 1 x 256 x 256. 447 for prompt_id in range(n_prompts): 448 this_tile_id = None 449 450 if have_boxes: 451 box = boxes[prompt_id] 452 center = np.array([(box[1] + box[3]) / 2, (box[0] + box[2]) / 2]).round().astype("int").tolist() 453 this_tile_id = tiling.coordinates_to_block_id(center) 454 tile = tiling.get_block_with_halo(this_tile_id, list(halo)).outer_block 455 offset = tile.begin 456 this_tile_shape = tile.shape 457 box_in_tile = np.array( 458 [ 459 max(box[1] - offset[0], 0), max(box[0] - offset[1], 0), 460 min(box[3] - offset[0], this_tile_shape[0]), min(box[2] - offset[1], this_tile_shape[1]) 461 ] 462 )[None] 463 if this_tile_id in box_to_tile: 464 box_to_tile[this_tile_id] = np.concatenate([box_to_tile[this_tile_id], box_in_tile]) 465 else: 466 box_to_tile[this_tile_id] = box_in_tile 467 468 if have_points: 469 point = points[prompt_id, 0][::-1].round().astype("int").tolist() 470 if this_tile_id is None: 471 this_tile_id = tiling.coordinates_to_block_id(point) 472 else: 473 assert this_tile_id == tiling.coordinates_to_block_id(point) 474 tile = tiling.get_block_with_halo(this_tile_id, list(halo)).outer_block 475 offset = tile.begin 476 point_in_tile = (points[prompt_id, 0] - np.array(offset)[::-1])[None, None] 477 label_in_tile = point_labels[prompt_id][None] 478 if this_tile_id in point_to_tile: 479 point_to_tile[this_tile_id] = np.concatenate([point_to_tile[this_tile_id], point_in_tile]) 480 label_to_tile[this_tile_id] = np.concatenate([label_to_tile[this_tile_id], label_in_tile]) 481 else: 482 point_to_tile[this_tile_id] = point_in_tile 483 label_to_tile[this_tile_id] = label_in_tile 484 485 # NOTE: logits are not yet supported. 486 tile_ids.append(this_tile_id) 487 488 # Find the tiles with prompts. 489 tile_ids = sorted(list(set(tile_ids))) 490 491 # Run batched inference for each tile. 492 masks = [] 493 # Additional variables needed for optimized memory mode. 494 id_offset = 0 495 for tile_id in tqdm(tile_ids, desc="Run batched inference"): 496 # Get the prompts for this tile. 497 tile_boxes = box_to_tile.get(tile_id) 498 tile_logits = logits_to_tile.get(tile_id) 499 tile_points, tile_labels = point_to_tile.get(tile_id), label_to_tile.get(tile_id) 500 501 # Set the correct embeddings, run inference. 502 predictor = set_precomputed(predictor, image_embeddings, tile_id=tile_id, i=i) 503 this_masks = batched_inference( 504 predictor=predictor, 505 image=None, 506 batch_size=batch_size, 507 boxes=tile_boxes, 508 points=tile_points, 509 point_labels=tile_labels, 510 multimasking=multimasking, 511 return_instance_segmentation=False, 512 segmentation_ids=segmentation_ids, 513 reduce_multimasking=reduce_multimasking, 514 logits_masks=tile_logits, 515 mask_threshold=mask_threshold, 516 ) 517 518 if optimize_memory: 519 # Apply NMS directly to get a segmentation. 520 segmentation = util.apply_nms(this_masks, **nms_kwargs) 521 fg_mask = segmentation != 0 522 segmentation[fg_mask] += id_offset 523 id_offset = segmentation.max() 524 masks.append(segmentation) 525 else: 526 # Add the offset for the current tile to the bounding box. 527 tile = tiling.get_block_with_halo(tile_id, list(halo)).outer_block 528 offset = np.array(tile.begin[::-1] + [0, 0]) 529 this_masks = [ 530 {**mask, "global_bbox": (np.array(mask["bbox"]) + offset).tolist()} for mask in this_masks 531 ] 532 masks.extend(this_masks) 533 534 # Try to keep the memory clean. 535 del this_masks 536 gc.collect() 537 538 if optimize_memory: 539 return _stitch_segmentation(masks, tile_ids, tiling, halo, output_shape=shape) 540 541 if return_instance_segmentation: 542 masks = util.mask_data_to_segmentation(masks, shape=shape, min_object_size=0) 543 return masks
@torch.no_grad()
def
batched_inference( predictor: segment_anything.predictor.SamPredictor, image: Optional[numpy.ndarray], batch_size: int, boxes: Optional[numpy.ndarray] = None, points: Optional[numpy.ndarray] = None, point_labels: Optional[numpy.ndarray] = None, multimasking: bool = False, embedding_path: Union[str, os.PathLike, NoneType] = None, return_instance_segmentation: bool = True, segmentation_ids: Optional[list] = None, reduce_multimasking: bool = True, logits_masks: Optional[torch.Tensor] = None, verbose_embeddings: bool = True, mask_threshold: Union[float, str, NoneType] = None, return_highres_logits: bool = False, i: Optional[int] = None) -> Union[List[List[Dict[str, Any]]], numpy.ndarray]:
159@torch.no_grad() 160def batched_inference( 161 predictor: SamPredictor, 162 image: Optional[np.ndarray], 163 batch_size: int, 164 boxes: Optional[np.ndarray] = None, 165 points: Optional[np.ndarray] = None, 166 point_labels: Optional[np.ndarray] = None, 167 multimasking: bool = False, 168 embedding_path: Optional[Union[str, os.PathLike]] = None, 169 return_instance_segmentation: bool = True, 170 segmentation_ids: Optional[list] = None, 171 reduce_multimasking: bool = True, 172 logits_masks: Optional[torch.Tensor] = None, 173 verbose_embeddings: bool = True, 174 mask_threshold: Optional[Union[float, str]] = None, 175 return_highres_logits: bool = False, 176 i: Optional[int] = None, 177) -> Union[List[List[Dict[str, Any]]], np.ndarray]: 178 """Run batched inference for input prompts. 179 180 Args: 181 predictor: The Segment Anything predictor. 182 image: The input image. If None, we assume that the image embeddings have already been computed. 183 batch_size: The batch size to use for inference. 184 boxes: The box prompts. Array of shape N_PROMPTS x 4. 185 The bounding boxes are represented by [MIN_X, MIN_Y, MAX_X, MAX_Y]. 186 points: The point prompt coordinates. Array of shape N_PROMPTS x 1 x 2. 187 The points are represented by their coordinates [X, Y], which are given in the last dimension. 188 point_labels: The point prompt labels. Array of shape N_PROMPTS x 1. 189 The labels are either 0 (negative prompt) or 1 (positive prompt). 190 multimasking: Whether to predict with 3 or 1 mask. By default, set to 'False'. 191 embedding_path: Cache path for the image embeddings. By default, computed on-the-fly. 192 return_instance_segmentation: Whether to return a instance segmentation 193 or the individual mask data. By default, set to 'True'. 194 segmentation_ids: Fixed segmentation ids to assign to the masks 195 derived from the prompts. 196 reduce_multimasking: Whether to choose the most likely masks with 197 highest ious from multimasking. By default, set to 'True'. 198 logits_masks: The logits masks. Array of shape N_PROMPTS x 1 x 256 x 256. 199 Whether to use the logits masks from previous segmentation. 200 verbose_embeddings: Whether to show progress outputs of computing image embeddings. 201 By default, set to 'True'. 202 mask_threshold: The theshold for binarizing masks based on the predicted values. 203 If None, the default threshold 0 is used. If "auto" is passed then the threshold is 204 determined with a local otsu filter. 205 return_highres_logits: Wheher to return high-resolution logits. 206 i: Index for the image data. Required if `image` has three spatial dimensions 207 or a time dimension and two spatial dimensions. 208 209 Returns: 210 The predicted segmentation masks. 211 """ 212 n_prompts, have_boxes, have_points, have_logits = _validate_inputs( 213 boxes, points, point_labels, multimasking, return_instance_segmentation, segmentation_ids, logits_masks 214 ) 215 216 # Compute the image embeddings. 217 if image is None: # This means the image embeddings are computed already. 218 # Call get image embeddings, this will throw an error if they have not yet been computed. 219 predictor.get_image_embedding() 220 else: 221 input_ = image if i is None else image[i] 222 # The input is always one 2d image. Deducing the dimensionality would read an RGB image as a volume. 223 image_embeddings = precompute_image_embeddings( 224 predictor, input_, embedding_path, ndim=2, verbose=verbose_embeddings 225 ) 226 set_precomputed(predictor, image_embeddings) 227 228 # Determine the number of batches. 229 n_batches = int(np.ceil(float(n_prompts) / batch_size)) 230 231 # Preprocess the prompts. 232 device = predictor.device 233 transform_function = ResizeLongestSide(1024) 234 image_shape = predictor.original_size 235 if have_boxes: 236 boxes = transform_function.apply_boxes(boxes, image_shape) 237 boxes = torch.tensor(boxes, dtype=torch.float32).to(device) 238 if have_points: 239 points = transform_function.apply_coords(points, image_shape) 240 points = torch.tensor(points, dtype=torch.float32).to(device) 241 point_labels = torch.tensor(point_labels, dtype=torch.float32).to(device) 242 243 masks = amg_utils.MaskData() 244 mask_threshold = predictor.model.mask_threshold if mask_threshold is None else mask_threshold 245 for batch_idx in range(n_batches): 246 batch_start = batch_idx * batch_size 247 batch_stop = min((batch_idx + 1) * batch_size, n_prompts) 248 249 batch_boxes = boxes[batch_start:batch_stop] if have_boxes else None 250 batch_points = points[batch_start:batch_stop] if have_points else None 251 batch_labels = point_labels[batch_start:batch_stop] if have_points else None 252 batch_logits = logits_masks[batch_start:batch_stop] if have_logits else None 253 254 batch_masks, batch_ious, batch_logits = predictor.predict_torch( 255 point_coords=batch_points, 256 point_labels=batch_labels, 257 boxes=batch_boxes, 258 mask_input=batch_logits, 259 multimask_output=multimasking, 260 return_logits=True, 261 ) 262 263 # If we expect to reduce the masks from multimasking and use multi-masking, 264 # then we need to select the most likely mask (according to the predicted IOU) here. 265 if reduce_multimasking and multimasking: 266 _, max_index = batch_ious.max(axis=1) 267 batch_masks = torch.cat([batch_masks[i, max_id][None] for i, max_id in enumerate(max_index)]).unsqueeze(1) 268 batch_ious = torch.cat([batch_ious[i, max_id][None] for i, max_id in enumerate(max_index)]).unsqueeze(1) 269 batch_logits = torch.cat([batch_logits[i, max_id][None] for i, max_id in enumerate(max_index)]).unsqueeze(1) 270 271 batch_data = _process_masks_for_batch( 272 batch_masks, batch_ious, batch_logits, return_highres_logits, mask_threshold 273 ) 274 masks.cat(batch_data) 275 276 # Mask data to records. 277 masks = [ 278 { 279 "segmentation": masks["masks"][idx], 280 "area": masks["masks"][idx].sum(), 281 "bbox": amg_utils.box_xyxy_to_xywh(masks["boxes"][idx]).tolist(), 282 "predicted_iou": masks["iou_preds"][idx].item(), 283 "stability_score": masks["stability_scores"][idx].item(), 284 "seg_id": idx + 1 if segmentation_ids is None else int(segmentation_ids[idx]), 285 "logits": masks["logits"][idx] 286 } 287 for idx in range(len(masks["masks"])) 288 ] 289 290 if return_instance_segmentation: 291 masks = util.mask_data_to_segmentation(masks, min_object_size=0) 292 return masks
Run batched inference for input prompts.
Arguments:
- predictor: The Segment Anything predictor.
- image: The input image. If None, we assume that the image embeddings have already been computed.
- batch_size: The batch size to use for inference.
- boxes: The box prompts. Array of shape N_PROMPTS x 4. The bounding boxes are represented by [MIN_X, MIN_Y, MAX_X, MAX_Y].
- points: The point prompt coordinates. Array of shape N_PROMPTS x 1 x 2. The points are represented by their coordinates [X, Y], which are given in the last dimension.
- point_labels: The point prompt labels. Array of shape N_PROMPTS x 1. The labels are either 0 (negative prompt) or 1 (positive prompt).
- multimasking: Whether to predict with 3 or 1 mask. By default, set to 'False'.
- embedding_path: Cache path for the image embeddings. By default, computed on-the-fly.
- return_instance_segmentation: Whether to return a instance segmentation or the individual mask data. By default, set to 'True'.
- segmentation_ids: Fixed segmentation ids to assign to the masks derived from the prompts.
- reduce_multimasking: Whether to choose the most likely masks with highest ious from multimasking. By default, set to 'True'.
- logits_masks: The logits masks. Array of shape N_PROMPTS x 1 x 256 x 256. Whether to use the logits masks from previous segmentation.
- verbose_embeddings: Whether to show progress outputs of computing image embeddings. By default, set to 'True'.
- mask_threshold: The theshold for binarizing masks based on the predicted values. If None, the default threshold 0 is used. If "auto" is passed then the threshold is determined with a local otsu filter.
- return_highres_logits: Wheher to return high-resolution logits.
- i: Index for the image data. Required if
imagehas three spatial dimensions or a time dimension and two spatial dimensions.
Returns:
The predicted segmentation masks.
@torch.no_grad()
def
batched_tiled_inference( predictor: segment_anything.predictor.SamPredictor, image: Optional[numpy.ndarray], batch_size: int, image_embeddings: Optional[Dict[str, Any]] = None, boxes: Optional[numpy.ndarray] = None, points: Optional[numpy.ndarray] = None, point_labels: Optional[numpy.ndarray] = None, multimasking: bool = False, embedding_path: Union[str, os.PathLike, NoneType] = None, return_instance_segmentation: bool = True, reduce_multimasking: bool = True, logits_masks: Optional[torch.Tensor] = None, verbose_embeddings: bool = True, mask_threshold: Union[float, str, NoneType] = None, tile_shape: Optional[Tuple[int, int]] = None, halo: Optional[Tuple[int, int]] = None, optimize_memory: bool = False, i: Optional[int] = None, **nms_kwargs) -> Union[List[List[Dict[str, Any]]], numpy.ndarray]:
363@torch.no_grad() 364def batched_tiled_inference( 365 predictor: SamPredictor, 366 image: Optional[np.ndarray], 367 batch_size: int, 368 image_embeddings: Optional[util.ImageEmbeddings] = None, 369 boxes: Optional[np.ndarray] = None, 370 points: Optional[np.ndarray] = None, 371 point_labels: Optional[np.ndarray] = None, 372 multimasking: bool = False, 373 embedding_path: Optional[Union[str, os.PathLike]] = None, 374 return_instance_segmentation: bool = True, 375 reduce_multimasking: bool = True, 376 logits_masks: Optional[torch.Tensor] = None, 377 verbose_embeddings: bool = True, 378 mask_threshold: Optional[Union[float, str]] = None, 379 tile_shape: Optional[Tuple[int, int]] = None, 380 halo: Optional[Tuple[int, int]] = None, 381 optimize_memory: bool = False, 382 i: Optional[int] = None, 383 **nms_kwargs, 384) -> Union[List[List[Dict[str, Any]]], np.ndarray]: 385 """Run batched inference for input prompts. 386 387 Args: 388 predictor: The Segment Anything predictor. 389 image: The input image. If None, we assume that the image embeddings have already been computed. 390 batch_size: The batch size to use for inference. 391 boxes: The box prompts. Array of shape N_PROMPTS x 4. 392 The bounding boxes are represented by [MIN_X, MIN_Y, MAX_X, MAX_Y]. 393 points: The point prompt coordinates. Array of shape N_PROMPTS x 1 x 2. 394 The points are represented by their coordinates [X, Y], which are given in the last dimension. 395 point_labels: The point prompt labels. Array of shape N_PROMPTS x 1. 396 The labels are either 0 (negative prompt) or 1 (positive prompt). 397 multimasking: Whether to predict with 3 or 1 mask. By default, set to 'False'. 398 embedding_path: Cache path for the image embeddings. By default, computed on-the-fly. 399 return_instance_segmentation: Whether to return a instance segmentation 400 or the individual mask data. By default, set to 'True'. 401 segmentation_ids: Fixed segmentation ids to assign to the masks 402 derived from the prompts. 403 reduce_multimasking: Whether to choose the most likely masks with 404 highest ious from multimasking. By default, set to 'True'. 405 logits_masks: The logits masks. Array of shape N_PROMPTS x 1 x 256 x 256. 406 Whether to use the logits masks from previous segmentation. 407 verbose_embeddings: Whether to show progress outputs of computing image embeddings. 408 By default, set to 'True'. 409 mask_threshold: The theshold for binarizing masks based on the predicted values. 410 If None, the default threshold 0 is used. If "auto" is passed then the threshold is 411 determined with a local otsu filter. 412 tile_shape: The tile shape for embedding prediction. 413 halo: The overlap of between tiles. 414 optimize_memory: Whether to optimize the memory usage. If set to True: 415 - NMS will be applied directly for each tile to reduce it to a per-tile instance segmentation. 416 - The per-tile segmentations will be stitched. 417 - The result will be returned as an instance segmentation. 418 i: Index for the image data. Required if `image` has three spatial dimensions 419 or a time dimension and two spatial dimensions. 420 nms_kwargs: Keyword arguments for the NMS operations that is used for optimize_memory=True. 421 Does not have any effect for optimize_memory=False. 422 423 Returns: 424 The predicted segmentation masks. 425 """ 426 # Validate inputs and get input prompt summary. 427 segmentation_ids = None 428 n_prompts, have_boxes, have_points, have_logits = _validate_inputs( 429 boxes, points, point_labels, multimasking, return_instance_segmentation, segmentation_ids, logits_masks 430 ) 431 if have_logits: 432 raise NotImplementedError 433 434 # Get the tiling parameters and compute embeddings if needed. 435 image_embeddings, shape, tile_shape, halo = _require_tiled_embeddings( 436 predictor, image, image_embeddings, embedding_path, tile_shape, halo, verbose_embeddings 437 ) 438 439 # Order the prompts by tile and then iterate over the tiles. 440 tiling = Blocking([0, 0], shape, tile_shape) 441 box_to_tile, point_to_tile, label_to_tile, logits_to_tile = {}, {}, {}, {} 442 tile_ids = [] 443 444 # Box prompts are in the format N x 4. Boxes are stored in order [MIN_X, MIN_Y, MAX_X, MAX_Y]. 445 # Points are in the Format N x 1 x 2 with coordinate order X, Y. 446 # Point labels are in the format N x 1. 447 # Mask prompts are in the format N x 1 x 256 x 256. 448 for prompt_id in range(n_prompts): 449 this_tile_id = None 450 451 if have_boxes: 452 box = boxes[prompt_id] 453 center = np.array([(box[1] + box[3]) / 2, (box[0] + box[2]) / 2]).round().astype("int").tolist() 454 this_tile_id = tiling.coordinates_to_block_id(center) 455 tile = tiling.get_block_with_halo(this_tile_id, list(halo)).outer_block 456 offset = tile.begin 457 this_tile_shape = tile.shape 458 box_in_tile = np.array( 459 [ 460 max(box[1] - offset[0], 0), max(box[0] - offset[1], 0), 461 min(box[3] - offset[0], this_tile_shape[0]), min(box[2] - offset[1], this_tile_shape[1]) 462 ] 463 )[None] 464 if this_tile_id in box_to_tile: 465 box_to_tile[this_tile_id] = np.concatenate([box_to_tile[this_tile_id], box_in_tile]) 466 else: 467 box_to_tile[this_tile_id] = box_in_tile 468 469 if have_points: 470 point = points[prompt_id, 0][::-1].round().astype("int").tolist() 471 if this_tile_id is None: 472 this_tile_id = tiling.coordinates_to_block_id(point) 473 else: 474 assert this_tile_id == tiling.coordinates_to_block_id(point) 475 tile = tiling.get_block_with_halo(this_tile_id, list(halo)).outer_block 476 offset = tile.begin 477 point_in_tile = (points[prompt_id, 0] - np.array(offset)[::-1])[None, None] 478 label_in_tile = point_labels[prompt_id][None] 479 if this_tile_id in point_to_tile: 480 point_to_tile[this_tile_id] = np.concatenate([point_to_tile[this_tile_id], point_in_tile]) 481 label_to_tile[this_tile_id] = np.concatenate([label_to_tile[this_tile_id], label_in_tile]) 482 else: 483 point_to_tile[this_tile_id] = point_in_tile 484 label_to_tile[this_tile_id] = label_in_tile 485 486 # NOTE: logits are not yet supported. 487 tile_ids.append(this_tile_id) 488 489 # Find the tiles with prompts. 490 tile_ids = sorted(list(set(tile_ids))) 491 492 # Run batched inference for each tile. 493 masks = [] 494 # Additional variables needed for optimized memory mode. 495 id_offset = 0 496 for tile_id in tqdm(tile_ids, desc="Run batched inference"): 497 # Get the prompts for this tile. 498 tile_boxes = box_to_tile.get(tile_id) 499 tile_logits = logits_to_tile.get(tile_id) 500 tile_points, tile_labels = point_to_tile.get(tile_id), label_to_tile.get(tile_id) 501 502 # Set the correct embeddings, run inference. 503 predictor = set_precomputed(predictor, image_embeddings, tile_id=tile_id, i=i) 504 this_masks = batched_inference( 505 predictor=predictor, 506 image=None, 507 batch_size=batch_size, 508 boxes=tile_boxes, 509 points=tile_points, 510 point_labels=tile_labels, 511 multimasking=multimasking, 512 return_instance_segmentation=False, 513 segmentation_ids=segmentation_ids, 514 reduce_multimasking=reduce_multimasking, 515 logits_masks=tile_logits, 516 mask_threshold=mask_threshold, 517 ) 518 519 if optimize_memory: 520 # Apply NMS directly to get a segmentation. 521 segmentation = util.apply_nms(this_masks, **nms_kwargs) 522 fg_mask = segmentation != 0 523 segmentation[fg_mask] += id_offset 524 id_offset = segmentation.max() 525 masks.append(segmentation) 526 else: 527 # Add the offset for the current tile to the bounding box. 528 tile = tiling.get_block_with_halo(tile_id, list(halo)).outer_block 529 offset = np.array(tile.begin[::-1] + [0, 0]) 530 this_masks = [ 531 {**mask, "global_bbox": (np.array(mask["bbox"]) + offset).tolist()} for mask in this_masks 532 ] 533 masks.extend(this_masks) 534 535 # Try to keep the memory clean. 536 del this_masks 537 gc.collect() 538 539 if optimize_memory: 540 return _stitch_segmentation(masks, tile_ids, tiling, halo, output_shape=shape) 541 542 if return_instance_segmentation: 543 masks = util.mask_data_to_segmentation(masks, shape=shape, min_object_size=0) 544 return masks
Run batched inference for input prompts.
Arguments:
- predictor: The Segment Anything predictor.
- image: The input image. If None, we assume that the image embeddings have already been computed.
- batch_size: The batch size to use for inference.
- boxes: The box prompts. Array of shape N_PROMPTS x 4. The bounding boxes are represented by [MIN_X, MIN_Y, MAX_X, MAX_Y].
- points: The point prompt coordinates. Array of shape N_PROMPTS x 1 x 2. The points are represented by their coordinates [X, Y], which are given in the last dimension.
- point_labels: The point prompt labels. Array of shape N_PROMPTS x 1. The labels are either 0 (negative prompt) or 1 (positive prompt).
- multimasking: Whether to predict with 3 or 1 mask. By default, set to 'False'.
- embedding_path: Cache path for the image embeddings. By default, computed on-the-fly.
- return_instance_segmentation: Whether to return a instance segmentation or the individual mask data. By default, set to 'True'.
- segmentation_ids: Fixed segmentation ids to assign to the masks derived from the prompts.
- reduce_multimasking: Whether to choose the most likely masks with highest ious from multimasking. By default, set to 'True'.
- logits_masks: The logits masks. Array of shape N_PROMPTS x 1 x 256 x 256. Whether to use the logits masks from previous segmentation.
- verbose_embeddings: Whether to show progress outputs of computing image embeddings. By default, set to 'True'.
- mask_threshold: The theshold for binarizing masks based on the predicted values. If None, the default threshold 0 is used. If "auto" is passed then the threshold is determined with a local otsu filter.
- tile_shape: The tile shape for embedding prediction.
- halo: The overlap of between tiles.
- optimize_memory: Whether to optimize the memory usage. If set to True:
- NMS will be applied directly for each tile to reduce it to a per-tile instance segmentation.
- The per-tile segmentations will be stitched.
- The result will be returned as an instance segmentation.
- i: Index for the image data. Required if
imagehas three spatial dimensions or a time dimension and two spatial dimensions. - nms_kwargs: Keyword arguments for the NMS operations that is used for optimize_memory=True. Does not have any effect for optimize_memory=False.
Returns:
The predicted segmentation masks.