micro_sam.v1.prompt_based_segmentation
Functions for prompt-based segmentation with Segment Anything.
1"""Functions for prompt-based segmentation with Segment Anything. 2""" 3 4import warnings 5from typing import Optional, Tuple 6 7import numpy as np 8 9from skimage.feature import peak_local_max 10from skimage.segmentation import find_boundaries 11 12from segment_anything.predictor import SamPredictor 13from segment_anything.utils.transforms import ResizeLongestSide 14 15import torch 16 17from bioimage_cpp.utils import Blocking 18from bioimage_cpp.filters import gaussian_smoothing 19from bioimage_cpp.distance import distance_transform 20 21from .. import util 22from .util import set_precomputed 23 24 25# 26# helper functions for translating mask inputs into other prompts 27# 28 29 30# compute the bounding box from a mask. SAM expects the following input: 31# box (np.ndarray or None): A length 4 array given a box prompt to the model, in XYXY format. 32def _compute_box_from_mask(mask, original_size=None, box_extension=0): 33 coords = np.where(mask == 1) 34 min_y, min_x = coords[0].min(), coords[1].min() 35 max_y, max_x = coords[0].max(), coords[1].max() 36 box = np.array([min_y, min_x, max_y + 1, max_x + 1]) 37 return _process_box(box, mask.shape, original_size=original_size, box_extension=box_extension) 38 39 40# sample points from a mask. SAM expects the following point inputs: 41def _compute_points_from_mask(mask, original_size, box_extension, use_single_point=False): 42 box = _compute_box_from_mask(mask, box_extension=box_extension) 43 44 # get slice and offset in python coordinate convention 45 bb = (slice(box[1], box[3]), slice(box[0], box[2])) 46 offset = np.array([box[1], box[0]]) 47 48 # crop the mask and compute distances 49 cropped_mask = mask[bb] 50 object_boundaries = find_boundaries(cropped_mask, mode="outer") 51 distances = gaussian_smoothing(distance_transform(object_boundaries == 0), sigma=1.0) 52 inner_distances = distances.copy() 53 cropped_mask = cropped_mask.astype("bool") 54 inner_distances[~cropped_mask] = 0.0 55 if use_single_point: 56 center = inner_distances.argmax() 57 center = np.unravel_index(center, inner_distances.shape) 58 point_coords = (center + offset)[None] 59 point_labels = np.ones(1, dtype="uint8") 60 return point_coords[:, ::-1], point_labels 61 62 outer_distances = distances.copy() 63 outer_distances[cropped_mask] = 0.0 64 65 # sample positives and negatives from the distance maxima 66 inner_maxima = peak_local_max(inner_distances, exclude_border=False, min_distance=3) 67 outer_maxima = peak_local_max(outer_distances, exclude_border=False, min_distance=5) 68 69 # derive the positive (=inner maxima) and negative (=outer maxima) points 70 point_coords = np.concatenate([inner_maxima, outer_maxima]).astype("float64") 71 point_coords += offset 72 73 if original_size is not None: 74 scale_factor = np.array([ 75 original_size[0] / float(mask.shape[0]), original_size[1] / float(mask.shape[1]) 76 ])[None] 77 point_coords *= scale_factor 78 79 # get the point labels 80 point_labels = np.concatenate( 81 [np.ones(len(inner_maxima), dtype="uint8"), np.zeros(len(outer_maxima), dtype="uint8")] 82 ) 83 return point_coords[:, ::-1], point_labels 84 85 86def _compute_logits_from_mask(mask, eps=1e-3): 87 88 def inv_sigmoid(x): 89 return np.log(x / (1 - x)) 90 91 # resize to the expected mask shape of SAM (256x256) 92 assert mask.ndim == 2 93 expected_shape = (256, 256) 94 95 # Resize the *binary* mask (instead of the inverse-sigmoid logits) to SAM's expected 96 # mask shape and re-binarize afterwards. This keeps small objects from being washed out 97 # by the antialiased downscaling that ResizeLongestSide applies, which otherwise makes 98 # the mask prompt too weak for small objects in large (and non-square) images. 99 binary_mask = (mask == 1).astype("float32") 100 101 if binary_mask.shape != expected_shape: 102 trafo = ResizeLongestSide(expected_shape[0]) 103 binary_mask = trafo.apply_image_torch(torch.from_numpy(binary_mask[None, None])) 104 binary_mask = binary_mask.numpy().squeeze() 105 106 if binary_mask.shape != expected_shape: # shape is not square -> pad the other side 107 h, w = binary_mask.shape 108 padh = expected_shape[0] - h 109 padw = expected_shape[1] - w 110 # IMPORTANT: need to pad with zero, otherwise SAM doesn't understand the padding 111 pad_width = ((0, padh), (0, padw)) 112 binary_mask = np.pad(binary_mask, pad_width, mode="constant", constant_values=0) 113 114 logits = np.where(binary_mask > 0.5, inv_sigmoid(1 - eps), inv_sigmoid(eps)).astype("float32") 115 logits = logits[None] 116 assert logits.shape == (1, 256, 256), f"{logits.shape}" 117 return logits 118 119 120# 121# other helper functions 122# 123 124 125def _process_box(box, shape, original_size=None, box_extension=0): 126 if box_extension == 0: # no extension 127 extension_y, extension_x = 0, 0 128 elif box_extension >= 1: # extension by a fixed factor 129 extension_y, extension_x = box_extension, box_extension 130 else: # extension by fraction of the box len 131 len_y, len_x = box[2] - box[0], box[3] - box[1] 132 extension_y, extension_x = box_extension * len_y, box_extension * len_x 133 134 box = np.array([ 135 max(box[1] - extension_x, 0), max(box[0] - extension_y, 0), 136 min(box[3] + extension_x, shape[1]), min(box[2] + extension_y, shape[0]), 137 ]) 138 139 if original_size is not None: 140 trafo = ResizeLongestSide(max(original_size)) 141 box = trafo.apply_boxes(box[None], (256, 256)).squeeze() 142 143 # round up the bounding box values 144 box = np.round(box).astype(int) 145 146 return box 147 148 149# Select the correct tile based on average of points 150# and bring the points to the coordinate system of the tile. 151# Discard points that are not in the tile and warn if this happens. 152def _points_to_tile(prompts, shape, tile_shape, halo): 153 points, labels = prompts 154 155 tiling = Blocking([0, 0], shape, tile_shape) 156 center = np.mean(points, axis=0).round().astype("int").tolist() 157 tile_id = tiling.coordinates_to_block_id(center) 158 159 tile = tiling.get_block_with_halo(tile_id, list(halo)).outer_block 160 offset = tile.begin 161 this_tile_shape = tile.shape 162 163 points_in_tile = points - np.array(offset) 164 labels_in_tile = labels 165 166 valid_point_mask = (points_in_tile >= 0).all(axis=1) 167 valid_point_mask = np.logical_and( 168 valid_point_mask, 169 np.logical_and( 170 points_in_tile[:, 0] < this_tile_shape[0], points_in_tile[:, 1] < this_tile_shape[1] 171 ) 172 ) 173 if not valid_point_mask.all(): 174 points_in_tile = points_in_tile[valid_point_mask] 175 labels_in_tile = labels_in_tile[valid_point_mask] 176 warnings.warn( 177 f"{(~valid_point_mask).sum()} points were not in the tile and are dropped" 178 ) 179 180 return tile_id, tile, (points_in_tile, labels_in_tile) 181 182 183def _box_to_tile(box, shape, tile_shape, halo): 184 tiling = Blocking([0, 0], shape, tile_shape) 185 center = np.array([(box[0] + box[2]) / 2, (box[1] + box[3]) / 2]).round().astype("int").tolist() 186 tile_id = tiling.coordinates_to_block_id(center) 187 188 tile = tiling.get_block_with_halo(tile_id, list(halo)).outer_block 189 offset = tile.begin 190 this_tile_shape = tile.shape 191 192 box_in_tile = np.array( 193 [ 194 max(box[0] - offset[0], 0), max(box[1] - offset[1], 0), 195 min(box[2] - offset[0], this_tile_shape[0]), min(box[3] - offset[1], this_tile_shape[1]) 196 ] 197 ) 198 199 return tile_id, tile, box_in_tile 200 201 202def _mask_to_tile(mask, shape, tile_shape, halo): 203 tiling = Blocking([0, 0], shape, tile_shape) 204 205 coords = np.where(mask) 206 center = np.array([np.mean(coords[0]), np.mean(coords[1])]).round().astype("int").tolist() 207 tile_id = tiling.coordinates_to_block_id(center) 208 209 tile = tiling.get_block_with_halo(tile_id, list(halo)).outer_block 210 bb = tuple(slice(beg, end) for beg, end in zip(tile.begin, tile.end)) 211 212 mask_in_tile = mask[bb] 213 return tile_id, tile, mask_in_tile 214 215 216def _initialize_predictor(predictor, image_embeddings, i, prompts, to_tile): 217 tile = None 218 219 # Set the precomputed state for tiled prediction. 220 if image_embeddings is not None and image_embeddings["input_size"] is None: 221 features = image_embeddings["features"] 222 shape, tile_shape, halo = features.attrs["shape"], features.attrs["tile_shape"], features.attrs["halo"] 223 tile_id, tile, prompts = to_tile(prompts, shape, tile_shape, halo) 224 set_precomputed(predictor, image_embeddings, i, tile_id=tile_id) 225 226 # Set the precomputed state for normal prediction. 227 elif image_embeddings is not None: 228 shape = image_embeddings["original_size"] 229 set_precomputed(predictor, image_embeddings, i) 230 231 else: 232 shape = predictor.original_size 233 234 return predictor, tile, prompts, shape 235 236 237def _tile_to_full_mask(mask, shape, tile): 238 full_mask = np.zeros(mask.shape[0:1] + tuple(shape), dtype=mask.dtype) 239 bb = tuple(slice(beg, end) for beg, end in zip(tile.begin, tile.end)) 240 full_mask[(slice(None),) + bb] = mask 241 return full_mask 242 243 244# 245# functions for prompted segmentation: 246# - segment_from_points: use point prompts as input 247# - segment_from_mask: use binary mask as input, support conversion to mask, box and point prompts 248# - segment_from_box: use box prompt as input 249# - segment_from_box_and_points: use box and point prompts as input 250# 251 252 253def segment_from_points( 254 predictor: SamPredictor, 255 points: np.ndarray, 256 labels: np.ndarray, 257 image_embeddings: Optional[util.ImageEmbeddings] = None, 258 i: Optional[int] = None, 259 multimask_output: bool = False, 260 return_all: bool = False, 261 use_best_multimask: Optional[bool] = None, 262): 263 """Segmentation from point prompts. 264 265 Args: 266 predictor: The segment anything predictor. 267 points: The point prompts given in the image coordinate system. 268 labels: The labels (positive or negative) associated with the points. 269 image_embeddings: Optional precomputed image embeddings. 270 Has to be passed if the predictor is not yet initialized. 271 i: Index for the image data. Required if the input data has three spatial dimensions 272 or a time dimension and two spatial dimensions. 273 multimask_output: Whether to return multiple or just a single mask. By default, set to 'False'. 274 return_all: Whether to return the score and logits in addition to the mask. By default, set to 'False'. 275 use_best_multimask: Whether to use multimask output and then choose the best mask. 276 By default this is used for a single positive point and not otherwise. 277 278 Returns: 279 The binary segmentation mask. 280 """ 281 predictor, tile, prompts, shape = _initialize_predictor( 282 predictor, image_embeddings, i, (points, labels), _points_to_tile 283 ) 284 points, labels = prompts 285 286 if use_best_multimask is None: 287 use_best_multimask = len(points) == 1 and labels[0] == 1 288 multimask_output_ = multimask_output or use_best_multimask 289 290 # predict the mask 291 mask, scores, logits = predictor.predict( 292 point_coords=points[:, ::-1], # SAM has reversed XY conventions 293 point_labels=labels, 294 multimask_output=multimask_output_, 295 ) 296 297 if use_best_multimask: 298 best_mask_id = np.argmax(scores) 299 mask = mask[best_mask_id][None] 300 301 if tile is not None: 302 mask = _tile_to_full_mask(mask, shape, tile) 303 304 if return_all: 305 return mask, scores, logits 306 else: 307 return mask 308 309 310def segment_from_mask( 311 predictor: SamPredictor, 312 mask: np.ndarray, 313 image_embeddings: Optional[util.ImageEmbeddings] = None, 314 i: Optional[int] = None, 315 use_box: bool = True, 316 use_mask: bool = True, 317 use_points: bool = False, 318 original_size: Optional[Tuple[int, ...]] = None, 319 multimask_output: bool = False, 320 return_all: bool = False, 321 return_logits: bool = False, 322 box_extension: float = 0.0, 323 box: Optional[np.ndarray] = None, 324 points: Optional[np.ndarray] = None, 325 labels: Optional[np.ndarray] = None, 326 use_single_point: bool = False, 327): 328 """Segmentation from a mask prompt. 329 330 Args: 331 predictor: The segment anything predictor. 332 mask: The mask used to derive prompts. 333 image_embeddings: Optional precomputed image embeddings. 334 Has to be passed if the predictor is not yet initialized. 335 i: Index for the image data. Required if the input data has three spatial dimensions 336 or a time dimension and two spatial dimensions. 337 use_box: Whether to derive the bounding box prompt from the mask. By default, set to 'True'. 338 use_mask: Whether to use the mask itself as prompt. By default, set to 'True'. 339 use_points: Whether to derive point prompts from the mask. By default, set to 'False'. 340 original_size: Full image shape. Use this if the mask that is being passed 341 downsampled compared to the original image. 342 multimask_output: Whether to return multiple or just a single mask. By default, set to 'False'. 343 return_all: Whether to return the score and logits in addition to the mask. By default, set to 'False'. 344 box_extension: Relative factor used to enlarge the bounding box prompt. 345 By default, does not enlarge the bounding box. 346 box: Precomputed bounding box. 347 points: Precomputed point prompts. 348 labels: Positive/negative labels corresponding to the point prompts. 349 use_single_point: Whether to derive just a single point from the mask. 350 In case use_points is true. 351 352 Returns: 353 The binary segmentation mask. 354 """ 355 prompts = (mask, box, points, labels) 356 357 def _to_tile(prompts, shape, tile_shape, halo): 358 mask, box, points, labels = prompts 359 tile_id, tile, mask = _mask_to_tile(mask, shape, tile_shape, halo) 360 if points is not None: 361 tile_id_points, tile, point_prompts = _points_to_tile((points, labels), shape, tile_shape, halo) 362 if tile_id_points != tile_id: 363 raise RuntimeError(f"Inconsistent tile ids for mask and point prompts: {tile_id_points} != {tile_id}.") 364 points, labels = point_prompts 365 if box is not None: 366 tile_id_box, tile, box = _box_to_tile(box, shape, tile_shape, halo) 367 if tile_id_box != tile_id: 368 raise RuntimeError(f"Inconsistent tile ids for mask and box prompts: {tile_id_box} != {tile_id}.") 369 return tile_id, tile, (mask, box, points, labels) 370 371 predictor, tile, prompts, shape = _initialize_predictor(predictor, image_embeddings, i, prompts, _to_tile) 372 mask, box, points, labels = prompts 373 374 if points is not None: 375 if labels is None: 376 raise ValueError("If points are passed you also need to pass labels.") 377 point_coords, point_labels = points, labels 378 379 elif use_points and mask.sum() != 0: 380 point_coords, point_labels = _compute_points_from_mask( 381 mask, original_size=original_size, box_extension=box_extension, 382 use_single_point=use_single_point, 383 ) 384 385 else: 386 point_coords, point_labels = None, None 387 388 if box is None: 389 box = _compute_box_from_mask( 390 mask, original_size=original_size, box_extension=box_extension 391 ) if use_box and mask.sum() != 0 else None 392 else: 393 box = _process_box(box, mask.shape, original_size=original_size, box_extension=box_extension) 394 395 logits = _compute_logits_from_mask(mask) if use_mask else None 396 397 mask, scores, logits = predictor.predict( 398 point_coords=point_coords, point_labels=point_labels, 399 mask_input=logits, box=box, 400 multimask_output=multimask_output, return_logits=return_logits 401 ) 402 403 if tile is not None: 404 mask = _tile_to_full_mask(mask, shape, tile) 405 406 if return_all: 407 return mask, scores, logits 408 else: 409 return mask 410 411 412def segment_from_box( 413 predictor: SamPredictor, 414 box: np.ndarray, 415 image_embeddings: Optional[util.ImageEmbeddings] = None, 416 i: Optional[int] = None, 417 multimask_output: bool = False, 418 return_all: bool = False, 419 box_extension: float = 0.0, 420): 421 """Segmentation from a box prompt. 422 423 Args: 424 predictor: The segment anything predictor. 425 box: The box prompt. 426 image_embeddings: Optional precomputed image embeddings. 427 Has to be passed if the predictor is not yet initialized. 428 i: Index for the image data. Required if the input data has three spatial dimensions 429 or a time dimension and two spatial dimensions. 430 multimask_output: Whether to return multiple or just a single mask. By default, set to 'False'. 431 return_all: Whether to return the score and logits in addition to the mask. By default, set to 'False'. 432 box_extension: Relative factor used to enlarge the bounding box prompt. 433 By default, does not enlarge the bounding box. 434 435 Returns: 436 The binary segmentation mask. 437 """ 438 predictor, tile, box, shape = _initialize_predictor( 439 predictor, image_embeddings, i, box, _box_to_tile 440 ) 441 mask, scores, logits = predictor.predict( 442 box=_process_box(box, shape, box_extension=box_extension), multimask_output=multimask_output 443 ) 444 445 if tile is not None: 446 mask = _tile_to_full_mask(mask, shape, tile) 447 448 if return_all: 449 return mask, scores, logits 450 else: 451 return mask 452 453 454def segment_from_box_and_points( 455 predictor: SamPredictor, 456 box: np.ndarray, 457 points: np.ndarray, 458 labels: np.ndarray, 459 image_embeddings: Optional[util.ImageEmbeddings] = None, 460 i: Optional[int] = None, 461 multimask_output: bool = False, 462 return_all: bool = False, 463): 464 """Segmentation from a box prompt and point prompts. 465 466 Args: 467 predictor: The segment anything predictor. 468 box: The box prompt. 469 points: The point prompts, given in the image coordinates system. 470 labels: The point labels, either positive or negative. 471 image_embeddings: Optional precomputed image embeddings. 472 Has to be passed if the predictor is not yet initialized. 473 i: Index for the image data. Required if the input data has three spatial dimensions 474 or a time dimension and two spatial dimensions. 475 multimask_output: Whether to return multiple or just a single mask. By default, set to 'False'. 476 return_all: Whether to return the score and logits in addition to the mask. By default, set to 'False'. 477 478 Returns: 479 The binary segmentation mask. 480 """ 481 def box_and_points_to_tile(prompts, shape, tile_shape, halo): 482 box, points, labels = prompts 483 tile_id, tile, point_prompts = _points_to_tile((points, labels), shape, tile_shape, halo) 484 points, labels = point_prompts 485 tile_id_box, tile, box = _box_to_tile(box, shape, tile_shape, halo) 486 if tile_id_box != tile_id: 487 raise RuntimeError(f"Inconsistent tile ids for box and point annotations: {tile_id_box} != {tile_id}.") 488 return tile_id, tile, (box, points, labels) 489 490 predictor, tile, prompts, shape = _initialize_predictor( 491 predictor, image_embeddings, i, (box, points, labels), box_and_points_to_tile 492 ) 493 box, points, labels = prompts 494 495 mask, scores, logits = predictor.predict( 496 point_coords=points[:, ::-1], # SAM has reversed XY conventions 497 point_labels=labels, 498 box=_process_box(box, shape), 499 multimask_output=multimask_output 500 ) 501 502 if tile is not None: 503 mask = _tile_to_full_mask(mask, shape, tile) 504 505 if return_all: 506 return mask, scores, logits 507 else: 508 return mask
def
segment_from_points( predictor: segment_anything.predictor.SamPredictor, points: numpy.ndarray, labels: numpy.ndarray, image_embeddings: Optional[Dict[str, Any]] = None, i: Optional[int] = None, multimask_output: bool = False, return_all: bool = False, use_best_multimask: Optional[bool] = None):
254def segment_from_points( 255 predictor: SamPredictor, 256 points: np.ndarray, 257 labels: np.ndarray, 258 image_embeddings: Optional[util.ImageEmbeddings] = None, 259 i: Optional[int] = None, 260 multimask_output: bool = False, 261 return_all: bool = False, 262 use_best_multimask: Optional[bool] = None, 263): 264 """Segmentation from point prompts. 265 266 Args: 267 predictor: The segment anything predictor. 268 points: The point prompts given in the image coordinate system. 269 labels: The labels (positive or negative) associated with the points. 270 image_embeddings: Optional precomputed image embeddings. 271 Has to be passed if the predictor is not yet initialized. 272 i: Index for the image data. Required if the input data has three spatial dimensions 273 or a time dimension and two spatial dimensions. 274 multimask_output: Whether to return multiple or just a single mask. By default, set to 'False'. 275 return_all: Whether to return the score and logits in addition to the mask. By default, set to 'False'. 276 use_best_multimask: Whether to use multimask output and then choose the best mask. 277 By default this is used for a single positive point and not otherwise. 278 279 Returns: 280 The binary segmentation mask. 281 """ 282 predictor, tile, prompts, shape = _initialize_predictor( 283 predictor, image_embeddings, i, (points, labels), _points_to_tile 284 ) 285 points, labels = prompts 286 287 if use_best_multimask is None: 288 use_best_multimask = len(points) == 1 and labels[0] == 1 289 multimask_output_ = multimask_output or use_best_multimask 290 291 # predict the mask 292 mask, scores, logits = predictor.predict( 293 point_coords=points[:, ::-1], # SAM has reversed XY conventions 294 point_labels=labels, 295 multimask_output=multimask_output_, 296 ) 297 298 if use_best_multimask: 299 best_mask_id = np.argmax(scores) 300 mask = mask[best_mask_id][None] 301 302 if tile is not None: 303 mask = _tile_to_full_mask(mask, shape, tile) 304 305 if return_all: 306 return mask, scores, logits 307 else: 308 return mask
Segmentation from point prompts.
Arguments:
- predictor: The segment anything predictor.
- points: The point prompts given in the image coordinate system.
- labels: The labels (positive or negative) associated with the points.
- image_embeddings: Optional precomputed image embeddings. Has to be passed if the predictor is not yet initialized.
- i: Index for the image data. Required if the input data has three spatial dimensions or a time dimension and two spatial dimensions.
- multimask_output: Whether to return multiple or just a single mask. By default, set to 'False'.
- return_all: Whether to return the score and logits in addition to the mask. By default, set to 'False'.
- use_best_multimask: Whether to use multimask output and then choose the best mask. By default this is used for a single positive point and not otherwise.
Returns:
The binary segmentation mask.
def
segment_from_mask( predictor: segment_anything.predictor.SamPredictor, mask: numpy.ndarray, image_embeddings: Optional[Dict[str, Any]] = None, i: Optional[int] = None, use_box: bool = True, use_mask: bool = True, use_points: bool = False, original_size: Optional[Tuple[int, ...]] = None, multimask_output: bool = False, return_all: bool = False, return_logits: bool = False, box_extension: float = 0.0, box: Optional[numpy.ndarray] = None, points: Optional[numpy.ndarray] = None, labels: Optional[numpy.ndarray] = None, use_single_point: bool = False):
311def segment_from_mask( 312 predictor: SamPredictor, 313 mask: np.ndarray, 314 image_embeddings: Optional[util.ImageEmbeddings] = None, 315 i: Optional[int] = None, 316 use_box: bool = True, 317 use_mask: bool = True, 318 use_points: bool = False, 319 original_size: Optional[Tuple[int, ...]] = None, 320 multimask_output: bool = False, 321 return_all: bool = False, 322 return_logits: bool = False, 323 box_extension: float = 0.0, 324 box: Optional[np.ndarray] = None, 325 points: Optional[np.ndarray] = None, 326 labels: Optional[np.ndarray] = None, 327 use_single_point: bool = False, 328): 329 """Segmentation from a mask prompt. 330 331 Args: 332 predictor: The segment anything predictor. 333 mask: The mask used to derive prompts. 334 image_embeddings: Optional precomputed image embeddings. 335 Has to be passed if the predictor is not yet initialized. 336 i: Index for the image data. Required if the input data has three spatial dimensions 337 or a time dimension and two spatial dimensions. 338 use_box: Whether to derive the bounding box prompt from the mask. By default, set to 'True'. 339 use_mask: Whether to use the mask itself as prompt. By default, set to 'True'. 340 use_points: Whether to derive point prompts from the mask. By default, set to 'False'. 341 original_size: Full image shape. Use this if the mask that is being passed 342 downsampled compared to the original image. 343 multimask_output: Whether to return multiple or just a single mask. By default, set to 'False'. 344 return_all: Whether to return the score and logits in addition to the mask. By default, set to 'False'. 345 box_extension: Relative factor used to enlarge the bounding box prompt. 346 By default, does not enlarge the bounding box. 347 box: Precomputed bounding box. 348 points: Precomputed point prompts. 349 labels: Positive/negative labels corresponding to the point prompts. 350 use_single_point: Whether to derive just a single point from the mask. 351 In case use_points is true. 352 353 Returns: 354 The binary segmentation mask. 355 """ 356 prompts = (mask, box, points, labels) 357 358 def _to_tile(prompts, shape, tile_shape, halo): 359 mask, box, points, labels = prompts 360 tile_id, tile, mask = _mask_to_tile(mask, shape, tile_shape, halo) 361 if points is not None: 362 tile_id_points, tile, point_prompts = _points_to_tile((points, labels), shape, tile_shape, halo) 363 if tile_id_points != tile_id: 364 raise RuntimeError(f"Inconsistent tile ids for mask and point prompts: {tile_id_points} != {tile_id}.") 365 points, labels = point_prompts 366 if box is not None: 367 tile_id_box, tile, box = _box_to_tile(box, shape, tile_shape, halo) 368 if tile_id_box != tile_id: 369 raise RuntimeError(f"Inconsistent tile ids for mask and box prompts: {tile_id_box} != {tile_id}.") 370 return tile_id, tile, (mask, box, points, labels) 371 372 predictor, tile, prompts, shape = _initialize_predictor(predictor, image_embeddings, i, prompts, _to_tile) 373 mask, box, points, labels = prompts 374 375 if points is not None: 376 if labels is None: 377 raise ValueError("If points are passed you also need to pass labels.") 378 point_coords, point_labels = points, labels 379 380 elif use_points and mask.sum() != 0: 381 point_coords, point_labels = _compute_points_from_mask( 382 mask, original_size=original_size, box_extension=box_extension, 383 use_single_point=use_single_point, 384 ) 385 386 else: 387 point_coords, point_labels = None, None 388 389 if box is None: 390 box = _compute_box_from_mask( 391 mask, original_size=original_size, box_extension=box_extension 392 ) if use_box and mask.sum() != 0 else None 393 else: 394 box = _process_box(box, mask.shape, original_size=original_size, box_extension=box_extension) 395 396 logits = _compute_logits_from_mask(mask) if use_mask else None 397 398 mask, scores, logits = predictor.predict( 399 point_coords=point_coords, point_labels=point_labels, 400 mask_input=logits, box=box, 401 multimask_output=multimask_output, return_logits=return_logits 402 ) 403 404 if tile is not None: 405 mask = _tile_to_full_mask(mask, shape, tile) 406 407 if return_all: 408 return mask, scores, logits 409 else: 410 return mask
Segmentation from a mask prompt.
Arguments:
- predictor: The segment anything predictor.
- mask: The mask used to derive prompts.
- image_embeddings: Optional precomputed image embeddings. Has to be passed if the predictor is not yet initialized.
- i: Index for the image data. Required if the input data has three spatial dimensions or a time dimension and two spatial dimensions.
- use_box: Whether to derive the bounding box prompt from the mask. By default, set to 'True'.
- use_mask: Whether to use the mask itself as prompt. By default, set to 'True'.
- use_points: Whether to derive point prompts from the mask. By default, set to 'False'.
- original_size: Full image shape. Use this if the mask that is being passed downsampled compared to the original image.
- multimask_output: Whether to return multiple or just a single mask. By default, set to 'False'.
- return_all: Whether to return the score and logits in addition to the mask. By default, set to 'False'.
- box_extension: Relative factor used to enlarge the bounding box prompt. By default, does not enlarge the bounding box.
- box: Precomputed bounding box.
- points: Precomputed point prompts.
- labels: Positive/negative labels corresponding to the point prompts.
- use_single_point: Whether to derive just a single point from the mask. In case use_points is true.
Returns:
The binary segmentation mask.
def
segment_from_box( predictor: segment_anything.predictor.SamPredictor, box: numpy.ndarray, image_embeddings: Optional[Dict[str, Any]] = None, i: Optional[int] = None, multimask_output: bool = False, return_all: bool = False, box_extension: float = 0.0):
413def segment_from_box( 414 predictor: SamPredictor, 415 box: np.ndarray, 416 image_embeddings: Optional[util.ImageEmbeddings] = None, 417 i: Optional[int] = None, 418 multimask_output: bool = False, 419 return_all: bool = False, 420 box_extension: float = 0.0, 421): 422 """Segmentation from a box prompt. 423 424 Args: 425 predictor: The segment anything predictor. 426 box: The box prompt. 427 image_embeddings: Optional precomputed image embeddings. 428 Has to be passed if the predictor is not yet initialized. 429 i: Index for the image data. Required if the input data has three spatial dimensions 430 or a time dimension and two spatial dimensions. 431 multimask_output: Whether to return multiple or just a single mask. By default, set to 'False'. 432 return_all: Whether to return the score and logits in addition to the mask. By default, set to 'False'. 433 box_extension: Relative factor used to enlarge the bounding box prompt. 434 By default, does not enlarge the bounding box. 435 436 Returns: 437 The binary segmentation mask. 438 """ 439 predictor, tile, box, shape = _initialize_predictor( 440 predictor, image_embeddings, i, box, _box_to_tile 441 ) 442 mask, scores, logits = predictor.predict( 443 box=_process_box(box, shape, box_extension=box_extension), multimask_output=multimask_output 444 ) 445 446 if tile is not None: 447 mask = _tile_to_full_mask(mask, shape, tile) 448 449 if return_all: 450 return mask, scores, logits 451 else: 452 return mask
Segmentation from a box prompt.
Arguments:
- predictor: The segment anything predictor.
- box: The box prompt.
- image_embeddings: Optional precomputed image embeddings. Has to be passed if the predictor is not yet initialized.
- i: Index for the image data. Required if the input data has three spatial dimensions or a time dimension and two spatial dimensions.
- multimask_output: Whether to return multiple or just a single mask. By default, set to 'False'.
- return_all: Whether to return the score and logits in addition to the mask. By default, set to 'False'.
- box_extension: Relative factor used to enlarge the bounding box prompt. By default, does not enlarge the bounding box.
Returns:
The binary segmentation mask.
def
segment_from_box_and_points( predictor: segment_anything.predictor.SamPredictor, box: numpy.ndarray, points: numpy.ndarray, labels: numpy.ndarray, image_embeddings: Optional[Dict[str, Any]] = None, i: Optional[int] = None, multimask_output: bool = False, return_all: bool = False):
455def segment_from_box_and_points( 456 predictor: SamPredictor, 457 box: np.ndarray, 458 points: np.ndarray, 459 labels: np.ndarray, 460 image_embeddings: Optional[util.ImageEmbeddings] = None, 461 i: Optional[int] = None, 462 multimask_output: bool = False, 463 return_all: bool = False, 464): 465 """Segmentation from a box prompt and point prompts. 466 467 Args: 468 predictor: The segment anything predictor. 469 box: The box prompt. 470 points: The point prompts, given in the image coordinates system. 471 labels: The point labels, either positive or negative. 472 image_embeddings: Optional precomputed image embeddings. 473 Has to be passed if the predictor is not yet initialized. 474 i: Index for the image data. Required if the input data has three spatial dimensions 475 or a time dimension and two spatial dimensions. 476 multimask_output: Whether to return multiple or just a single mask. By default, set to 'False'. 477 return_all: Whether to return the score and logits in addition to the mask. By default, set to 'False'. 478 479 Returns: 480 The binary segmentation mask. 481 """ 482 def box_and_points_to_tile(prompts, shape, tile_shape, halo): 483 box, points, labels = prompts 484 tile_id, tile, point_prompts = _points_to_tile((points, labels), shape, tile_shape, halo) 485 points, labels = point_prompts 486 tile_id_box, tile, box = _box_to_tile(box, shape, tile_shape, halo) 487 if tile_id_box != tile_id: 488 raise RuntimeError(f"Inconsistent tile ids for box and point annotations: {tile_id_box} != {tile_id}.") 489 return tile_id, tile, (box, points, labels) 490 491 predictor, tile, prompts, shape = _initialize_predictor( 492 predictor, image_embeddings, i, (box, points, labels), box_and_points_to_tile 493 ) 494 box, points, labels = prompts 495 496 mask, scores, logits = predictor.predict( 497 point_coords=points[:, ::-1], # SAM has reversed XY conventions 498 point_labels=labels, 499 box=_process_box(box, shape), 500 multimask_output=multimask_output 501 ) 502 503 if tile is not None: 504 mask = _tile_to_full_mask(mask, shape, tile) 505 506 if return_all: 507 return mask, scores, logits 508 else: 509 return mask
Segmentation from a box prompt and point prompts.
Arguments:
- predictor: The segment anything predictor.
- box: The box prompt.
- points: The point prompts, given in the image coordinates system.
- labels: The point labels, either positive or negative.
- image_embeddings: Optional precomputed image embeddings. Has to be passed if the predictor is not yet initialized.
- i: Index for the image data. Required if the input data has three spatial dimensions or a time dimension and two spatial dimensions.
- multimask_output: Whether to return multiple or just a single mask. By default, set to 'False'.
- return_all: Whether to return the score and logits in addition to the mask. By default, set to 'False'.
Returns:
The binary segmentation mask.