neuro-sam 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. neuro_sam/__init__.py +1 -0
  2. neuro_sam/brightest_path_lib/__init__.py +5 -0
  3. neuro_sam/brightest_path_lib/algorithm/__init__.py +3 -0
  4. neuro_sam/brightest_path_lib/algorithm/astar.py +586 -0
  5. neuro_sam/brightest_path_lib/algorithm/waypointastar.py +449 -0
  6. neuro_sam/brightest_path_lib/algorithm/waypointastar_speedup.py +1007 -0
  7. neuro_sam/brightest_path_lib/connected_componen.py +329 -0
  8. neuro_sam/brightest_path_lib/cost/__init__.py +8 -0
  9. neuro_sam/brightest_path_lib/cost/cost.py +33 -0
  10. neuro_sam/brightest_path_lib/cost/reciprocal.py +90 -0
  11. neuro_sam/brightest_path_lib/cost/reciprocal_transonic.py +86 -0
  12. neuro_sam/brightest_path_lib/heuristic/__init__.py +2 -0
  13. neuro_sam/brightest_path_lib/heuristic/euclidean.py +101 -0
  14. neuro_sam/brightest_path_lib/heuristic/heuristic.py +29 -0
  15. neuro_sam/brightest_path_lib/image/__init__.py +1 -0
  16. neuro_sam/brightest_path_lib/image/stats.py +197 -0
  17. neuro_sam/brightest_path_lib/input/__init__.py +1 -0
  18. neuro_sam/brightest_path_lib/input/inputs.py +14 -0
  19. neuro_sam/brightest_path_lib/node/__init__.py +2 -0
  20. neuro_sam/brightest_path_lib/node/bidirectional_node.py +240 -0
  21. neuro_sam/brightest_path_lib/node/node.py +125 -0
  22. neuro_sam/brightest_path_lib/visualization/__init__.py +4 -0
  23. neuro_sam/brightest_path_lib/visualization/flythrough.py +133 -0
  24. neuro_sam/brightest_path_lib/visualization/flythrough_all.py +394 -0
  25. neuro_sam/brightest_path_lib/visualization/tube_data.py +385 -0
  26. neuro_sam/brightest_path_lib/visualization/tube_flythrough.py +227 -0
  27. neuro_sam/napari_utils/anisotropic_scaling.py +503 -0
  28. neuro_sam/napari_utils/color_utils.py +135 -0
  29. neuro_sam/napari_utils/contrasting_color_system.py +169 -0
  30. neuro_sam/napari_utils/main_widget.py +1016 -0
  31. neuro_sam/napari_utils/path_tracing_module.py +1016 -0
  32. neuro_sam/napari_utils/punet_widget.py +424 -0
  33. neuro_sam/napari_utils/segmentation_model.py +769 -0
  34. neuro_sam/napari_utils/segmentation_module.py +649 -0
  35. neuro_sam/napari_utils/visualization_module.py +574 -0
  36. neuro_sam/plugin.py +260 -0
  37. neuro_sam/punet/__init__.py +0 -0
  38. neuro_sam/punet/deepd3_model.py +231 -0
  39. neuro_sam/punet/prob_unet_deepd3.py +431 -0
  40. neuro_sam/punet/prob_unet_with_tversky.py +375 -0
  41. neuro_sam/punet/punet_inference.py +236 -0
  42. neuro_sam/punet/run_inference.py +145 -0
  43. neuro_sam/punet/unet_blocks.py +81 -0
  44. neuro_sam/punet/utils.py +52 -0
  45. neuro_sam-0.1.0.dist-info/METADATA +269 -0
  46. neuro_sam-0.1.0.dist-info/RECORD +93 -0
  47. neuro_sam-0.1.0.dist-info/WHEEL +5 -0
  48. neuro_sam-0.1.0.dist-info/entry_points.txt +2 -0
  49. neuro_sam-0.1.0.dist-info/licenses/LICENSE +21 -0
  50. neuro_sam-0.1.0.dist-info/top_level.txt +2 -0
  51. sam2/__init__.py +11 -0
  52. sam2/automatic_mask_generator.py +454 -0
  53. sam2/benchmark.py +92 -0
  54. sam2/build_sam.py +174 -0
  55. sam2/configs/sam2/sam2_hiera_b+.yaml +113 -0
  56. sam2/configs/sam2/sam2_hiera_l.yaml +117 -0
  57. sam2/configs/sam2/sam2_hiera_s.yaml +116 -0
  58. sam2/configs/sam2/sam2_hiera_t.yaml +118 -0
  59. sam2/configs/sam2.1/sam2.1_hiera_b+.yaml +116 -0
  60. sam2/configs/sam2.1/sam2.1_hiera_l.yaml +120 -0
  61. sam2/configs/sam2.1/sam2.1_hiera_s.yaml +119 -0
  62. sam2/configs/sam2.1/sam2.1_hiera_t.yaml +121 -0
  63. sam2/configs/sam2.1_training/sam2.1_hiera_b+_MOSE_finetune.yaml +339 -0
  64. sam2/configs/train.yaml +335 -0
  65. sam2/modeling/__init__.py +5 -0
  66. sam2/modeling/backbones/__init__.py +5 -0
  67. sam2/modeling/backbones/hieradet.py +317 -0
  68. sam2/modeling/backbones/image_encoder.py +134 -0
  69. sam2/modeling/backbones/utils.py +93 -0
  70. sam2/modeling/memory_attention.py +169 -0
  71. sam2/modeling/memory_encoder.py +181 -0
  72. sam2/modeling/position_encoding.py +239 -0
  73. sam2/modeling/sam/__init__.py +5 -0
  74. sam2/modeling/sam/mask_decoder.py +295 -0
  75. sam2/modeling/sam/prompt_encoder.py +202 -0
  76. sam2/modeling/sam/transformer.py +311 -0
  77. sam2/modeling/sam2_base.py +911 -0
  78. sam2/modeling/sam2_utils.py +323 -0
  79. sam2/sam2.1_hiera_b+.yaml +116 -0
  80. sam2/sam2.1_hiera_l.yaml +120 -0
  81. sam2/sam2.1_hiera_s.yaml +119 -0
  82. sam2/sam2.1_hiera_t.yaml +121 -0
  83. sam2/sam2_hiera_b+.yaml +113 -0
  84. sam2/sam2_hiera_l.yaml +117 -0
  85. sam2/sam2_hiera_s.yaml +116 -0
  86. sam2/sam2_hiera_t.yaml +118 -0
  87. sam2/sam2_image_predictor.py +475 -0
  88. sam2/sam2_video_predictor.py +1222 -0
  89. sam2/sam2_video_predictor_legacy.py +1172 -0
  90. sam2/utils/__init__.py +5 -0
  91. sam2/utils/amg.py +348 -0
  92. sam2/utils/misc.py +349 -0
  93. sam2/utils/transforms.py +118 -0
@@ -0,0 +1,475 @@
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import logging
8
+
9
+ from typing import List, Optional, Tuple, Union
10
+
11
+ import numpy as np
12
+ import torch
13
+ from PIL.Image import Image
14
+ import torch.nn as nn
15
+ from sam2.modeling.sam2_base import SAM2Base
16
+
17
+ from sam2.utils.transforms import SAM2Transforms
18
+
19
+
20
+ class SAM2ImagePredictor:
21
+ def __init__(
22
+ self,
23
+ sam_model: SAM2Base,
24
+ mask_threshold=0.0,
25
+ max_hole_area=0.0,
26
+ max_sprinkle_area=0.0,
27
+ **kwargs,
28
+ ) -> None:
29
+ """
30
+ Uses SAM-2 to calculate the image embedding for an image, and then
31
+ allow repeated, efficient mask prediction given prompts.
32
+
33
+ Arguments:
34
+ sam_model (Sam-2): The model to use for mask prediction.
35
+ mask_threshold (float): The threshold to use when converting mask logits
36
+ to binary masks. Masks are thresholded at 0 by default.
37
+ max_hole_area (int): If max_hole_area > 0, we fill small holes in up to
38
+ the maximum area of max_hole_area in low_res_masks.
39
+ max_sprinkle_area (int): If max_sprinkle_area > 0, we remove small sprinkles up to
40
+ the maximum area of max_sprinkle_area in low_res_masks.
41
+ """
42
+
43
+ super().__init__()
44
+ if isinstance(sam_model, nn.DataParallel):
45
+ self.model = sam_model.module
46
+ else:
47
+ self.model = sam_model
48
+ # self.model = sam_model
49
+ self._transforms = SAM2Transforms(
50
+ resolution=self.model.image_size,
51
+ mask_threshold=mask_threshold,
52
+ max_hole_area=max_hole_area,
53
+ max_sprinkle_area=max_sprinkle_area,
54
+ )
55
+
56
+ # Predictor state
57
+ self._is_image_set = False
58
+ self._features = None
59
+ self._orig_hw = None
60
+ # Whether the predictor is set for single image or a batch of images
61
+ self._is_batch = False
62
+
63
+ # Predictor config
64
+ self.mask_threshold = mask_threshold
65
+
66
+ # Spatial dim for backbone feature maps
67
+ hires_size = self.model.image_size // 4
68
+ self._bb_feat_sizes = [[hires_size // (2**k)]*2 for k in range(3)]
69
+
70
+ # # Spatial dim for backbone feature maps
71
+ # self._bb_feat_sizes = [
72
+ # (256, 256),
73
+ # (128, 128),
74
+ # (64, 64),
75
+ # ]
76
+
77
+ @classmethod
78
+ def from_pretrained(cls, model_id: str, **kwargs) -> "SAM2ImagePredictor":
79
+ """
80
+ Load a pretrained model from the Hugging Face hub.
81
+
82
+ Arguments:
83
+ model_id (str): The Hugging Face repository ID.
84
+ **kwargs: Additional arguments to pass to the model constructor.
85
+
86
+ Returns:
87
+ (SAM2ImagePredictor): The loaded model.
88
+ """
89
+ from sam2.build_sam import build_sam2_hf
90
+
91
+ sam_model = build_sam2_hf(model_id, **kwargs)
92
+ return cls(sam_model, **kwargs)
93
+
94
+ @torch.no_grad()
95
+ def set_image(
96
+ self,
97
+ image: Union[np.ndarray, Image],
98
+ ) -> None:
99
+ """
100
+ Calculates the image embeddings for the provided image, allowing
101
+ masks to be predicted with the 'predict' method.
102
+
103
+ Arguments:
104
+ image (np.ndarray or PIL Image): The input image to embed in RGB format. The image should be in HWC format if np.ndarray, or WHC format if PIL Image
105
+ with pixel values in [0, 255].
106
+ image_format (str): The color format of the image, in ['RGB', 'BGR'].
107
+ """
108
+ self.reset_predictor()
109
+ # Transform the image to the form expected by the model
110
+ if isinstance(image, np.ndarray):
111
+ logging.info("For numpy array image, we assume (HxWxC) format")
112
+ self._orig_hw = [image.shape[:2]]
113
+ elif isinstance(image, Image):
114
+ w, h = image.size
115
+ self._orig_hw = [(h, w)]
116
+ else:
117
+ raise NotImplementedError("Image format not supported")
118
+
119
+ input_image = self._transforms(image)
120
+ input_image = input_image[None, ...].to(self.device)
121
+
122
+ assert (
123
+ len(input_image.shape) == 4 and input_image.shape[1] == 3
124
+ ), f"input_image must be of size 1x3xHxW, got {input_image.shape}"
125
+ logging.info("Computing image embeddings for the provided image...")
126
+ backbone_out = self.model.forward_image(input_image)
127
+ _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out)
128
+ # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos
129
+ if self.model.directly_add_no_mem_embed:
130
+ vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
131
+
132
+ feats = [
133
+ feat.permute(1, 2, 0).view(1, -1, *feat_size)
134
+ for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1])
135
+ ][::-1]
136
+ self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
137
+ self._is_image_set = True
138
+ logging.info("Image embeddings computed.")
139
+
140
+ @torch.no_grad()
141
+ def set_image_batch(
142
+ self,
143
+ image_list: List[Union[np.ndarray]],
144
+ ) -> None:
145
+ """
146
+ Calculates the image embeddings for the provided image batch, allowing
147
+ masks to be predicted with the 'predict_batch' method.
148
+
149
+ Arguments:
150
+ image_list (List[np.ndarray]): The input images to embed in RGB format. The image should be in HWC format if np.ndarray
151
+ with pixel values in [0, 255].
152
+ """
153
+ self.reset_predictor()
154
+ # assert isinstance(image_list, list)
155
+ self._orig_hw = []
156
+ for image in image_list:
157
+ # assert isinstance(
158
+ # image, np.ndarray
159
+ # ), "Images are expected to be an np.ndarray in RGB format, and of shape HWC"
160
+ self._orig_hw.append(image.shape[:2])
161
+ # Transform the image to the form expected by the model
162
+ img_batch = self._transforms.forward_batch(image_list)
163
+ img_batch = img_batch.to(self.device)
164
+ batch_size = img_batch.shape[0]
165
+ assert (
166
+ len(img_batch.shape) == 4 and img_batch.shape[1] == 3
167
+ ), f"img_batch must be of size Bx3xHxW, got {img_batch.shape}"
168
+ logging.info("Computing image embeddings for the provided images...")
169
+ backbone_out = self.model.forward_image(img_batch)
170
+ _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out)
171
+ # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos
172
+ if self.model.directly_add_no_mem_embed:
173
+ vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
174
+
175
+ feats = [
176
+ feat.permute(1, 2, 0).view(batch_size, -1, *feat_size)
177
+ for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1])
178
+ ][::-1]
179
+ self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
180
+ self._is_image_set = True
181
+ self._is_batch = True
182
+ logging.info("Image embeddings computed.")
183
+
184
+ def predict_batch(
185
+ self,
186
+ point_coords_batch: List[np.ndarray] = None,
187
+ point_labels_batch: List[np.ndarray] = None,
188
+ box_batch: List[np.ndarray] = None,
189
+ mask_input_batch: List[np.ndarray] = None,
190
+ multimask_output: bool = True,
191
+ return_logits: bool = False,
192
+ normalize_coords=True,
193
+ ) -> Tuple[List[np.ndarray], List[np.ndarray], List[np.ndarray]]:
194
+ """This function is very similar to predict(...), however it is used for batched mode, when the model is expected to generate predictions on multiple images.
195
+ It returns a tuple of lists of masks, ious, and low_res_masks_logits.
196
+ """
197
+ assert self._is_batch, "This function should only be used when in batched mode"
198
+ if not self._is_image_set:
199
+ raise RuntimeError(
200
+ "An image must be set with .set_image_batch(...) before mask prediction."
201
+ )
202
+ num_images = len(self._features["image_embed"])
203
+ all_masks = []
204
+ all_ious = []
205
+ all_low_res_masks = []
206
+ for img_idx in range(num_images):
207
+ # Transform input prompts
208
+ point_coords = (
209
+ point_coords_batch[img_idx] if point_coords_batch is not None else None
210
+ )
211
+ point_labels = (
212
+ point_labels_batch[img_idx] if point_labels_batch is not None else None
213
+ )
214
+ box = box_batch[img_idx] if box_batch is not None else None
215
+ mask_input = (
216
+ mask_input_batch[img_idx] if mask_input_batch is not None else None
217
+ )
218
+ mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts(
219
+ point_coords,
220
+ point_labels,
221
+ box,
222
+ mask_input,
223
+ normalize_coords,
224
+ img_idx=img_idx,
225
+ )
226
+ masks, iou_predictions, low_res_masks = self._predict(
227
+ unnorm_coords,
228
+ labels,
229
+ unnorm_box,
230
+ mask_input,
231
+ multimask_output,
232
+ return_logits=return_logits,
233
+ img_idx=img_idx,
234
+ )
235
+ masks_np = masks.squeeze(0).float().detach().cpu().numpy()
236
+ iou_predictions_np = (
237
+ iou_predictions.squeeze(0).float().detach().cpu().numpy()
238
+ )
239
+ low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy()
240
+ all_masks.append(masks_np)
241
+ all_ious.append(iou_predictions_np)
242
+ all_low_res_masks.append(low_res_masks_np)
243
+
244
+ return all_masks, all_ious, all_low_res_masks
245
+
246
+ def predict(
247
+ self,
248
+ point_coords: Optional[np.ndarray] = None,
249
+ point_labels: Optional[np.ndarray] = None,
250
+ box: Optional[np.ndarray] = None,
251
+ mask_input: Optional[np.ndarray] = None,
252
+ multimask_output: bool = True,
253
+ return_logits: bool = False,
254
+ normalize_coords=True,
255
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
256
+ """
257
+ Predict masks for the given input prompts, using the currently set image.
258
+
259
+ Arguments:
260
+ point_coords (np.ndarray or None): A Nx2 array of point prompts to the
261
+ model. Each point is in (X,Y) in pixels.
262
+ point_labels (np.ndarray or None): A length N array of labels for the
263
+ point prompts. 1 indicates a foreground point and 0 indicates a
264
+ background point.
265
+ box (np.ndarray or None): A length 4 array given a box prompt to the
266
+ model, in XYXY format.
267
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
268
+ coming from a previous prediction iteration. Has form 1xHxW, where
269
+ for SAM, H=W=256.
270
+ multimask_output (bool): If true, the model will return three masks.
271
+ For ambiguous input prompts (such as a single click), this will often
272
+ produce better masks than a single prediction. If only a single
273
+ mask is needed, the model's predicted quality score can be used
274
+ to select the best mask. For non-ambiguous prompts, such as multiple
275
+ input prompts, multimask_output=False can give better results.
276
+ return_logits (bool): If true, returns un-thresholded masks logits
277
+ instead of a binary mask.
278
+ normalize_coords (bool): If true, the point coordinates will be normalized to the range [0,1] and point_coords is expected to be wrt. image dimensions.
279
+
280
+ Returns:
281
+ (np.ndarray): The output masks in CxHxW format, where C is the
282
+ number of masks, and (H, W) is the original image size.
283
+ (np.ndarray): An array of length C containing the model's
284
+ predictions for the quality of each mask.
285
+ (np.ndarray): An array of shape CxHxW, where C is the number
286
+ of masks and H=W=256. These low resolution logits can be passed to
287
+ a subsequent iteration as mask input.
288
+ """
289
+ if not self._is_image_set:
290
+ raise RuntimeError(
291
+ "An image must be set with .set_image(...) before mask prediction."
292
+ )
293
+
294
+ # Transform input prompts
295
+
296
+ mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts(
297
+ point_coords, point_labels, box, mask_input, normalize_coords
298
+ )
299
+
300
+ masks, iou_predictions, low_res_masks = self._predict(
301
+ unnorm_coords,
302
+ labels,
303
+ unnorm_box,
304
+ mask_input,
305
+ multimask_output,
306
+ return_logits=return_logits,
307
+ )
308
+
309
+ masks_np = masks.squeeze(0).float().detach().cpu().numpy()
310
+ iou_predictions_np = iou_predictions.squeeze(0).float().detach().cpu().numpy()
311
+ low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy()
312
+ return masks_np, iou_predictions_np, low_res_masks_np
313
+
314
+ def _prep_prompts(
315
+ self, point_coords, point_labels, box, mask_logits, normalize_coords, img_idx=-1
316
+ ):
317
+
318
+ unnorm_coords, labels, unnorm_box, mask_input = None, None, None, None
319
+ if point_coords is not None:
320
+ assert (
321
+ point_labels is not None
322
+ ), "point_labels must be supplied if point_coords is supplied."
323
+ point_coords = torch.as_tensor(
324
+ point_coords, dtype=torch.float, device=self.device
325
+ )
326
+ unnorm_coords = self._transforms.transform_coords(
327
+ point_coords, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx]
328
+ )
329
+ labels = torch.as_tensor(point_labels, dtype=torch.int, device=self.device)
330
+ if len(unnorm_coords.shape) == 2:
331
+ unnorm_coords, labels = unnorm_coords[None, ...], labels[None, ...]
332
+ if box is not None:
333
+ box = torch.as_tensor(box, dtype=torch.float, device=self.device)
334
+ unnorm_box = self._transforms.transform_boxes(
335
+ box, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx]
336
+ ) # Bx2x2
337
+ if mask_logits is not None:
338
+ mask_input = torch.as_tensor(
339
+ mask_logits, dtype=torch.float, device=self.device
340
+ )
341
+ if len(mask_input.shape) == 3:
342
+ mask_input = mask_input[None, :, :, :]
343
+ return mask_input, unnorm_coords, labels, unnorm_box
344
+
345
+ @torch.no_grad()
346
+ def _predict(
347
+ self,
348
+ point_coords: Optional[torch.Tensor],
349
+ point_labels: Optional[torch.Tensor],
350
+ boxes: Optional[torch.Tensor] = None,
351
+ mask_input: Optional[torch.Tensor] = None,
352
+ multimask_output: bool = True,
353
+ return_logits: bool = False,
354
+ img_idx: int = -1,
355
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
356
+ """
357
+ Predict masks for the given input prompts, using the currently set image.
358
+ Input prompts are batched torch tensors and are expected to already be
359
+ transformed to the input frame using SAM2Transforms.
360
+
361
+ Arguments:
362
+ point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the
363
+ model. Each point is in (X,Y) in pixels.
364
+ point_labels (torch.Tensor or None): A BxN array of labels for the
365
+ point prompts. 1 indicates a foreground point and 0 indicates a
366
+ background point.
367
+ boxes (np.ndarray or None): A Bx4 array given a box prompt to the
368
+ model, in XYXY format.
369
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
370
+ coming from a previous prediction iteration. Has form Bx1xHxW, where
371
+ for SAM, H=W=256. Masks returned by a previous iteration of the
372
+ predict method do not need further transformation.
373
+ multimask_output (bool): If true, the model will return three masks.
374
+ For ambiguous input prompts (such as a single click), this will often
375
+ produce better masks than a single prediction. If only a single
376
+ mask is needed, the model's predicted quality score can be used
377
+ to select the best mask. For non-ambiguous prompts, such as multiple
378
+ input prompts, multimask_output=False can give better results.
379
+ return_logits (bool): If true, returns un-thresholded masks logits
380
+ instead of a binary mask.
381
+
382
+ Returns:
383
+ (torch.Tensor): The output masks in BxCxHxW format, where C is the
384
+ number of masks, and (H, W) is the original image size.
385
+ (torch.Tensor): An array of shape BxC containing the model's
386
+ predictions for the quality of each mask.
387
+ (torch.Tensor): An array of shape BxCxHxW, where C is the number
388
+ of masks and H=W=256. These low res logits can be passed to
389
+ a subsequent iteration as mask input.
390
+ """
391
+ if not self._is_image_set:
392
+ raise RuntimeError(
393
+ "An image must be set with .set_image(...) before mask prediction."
394
+ )
395
+
396
+ if point_coords is not None:
397
+ concat_points = (point_coords, point_labels)
398
+ else:
399
+ concat_points = None
400
+
401
+ # Embed prompts
402
+ if boxes is not None:
403
+ box_coords = boxes.reshape(-1, 2, 2)
404
+ box_labels = torch.tensor([[2, 3]], dtype=torch.int, device=boxes.device)
405
+ box_labels = box_labels.repeat(boxes.size(0), 1)
406
+ # we merge "boxes" and "points" into a single "concat_points" input (where
407
+ # boxes are added at the beginning) to sam_prompt_encoder
408
+ if concat_points is not None:
409
+ concat_coords = torch.cat([box_coords, concat_points[0]], dim=1)
410
+ concat_labels = torch.cat([box_labels, concat_points[1]], dim=1)
411
+ concat_points = (concat_coords, concat_labels)
412
+ else:
413
+ concat_points = (box_coords, box_labels)
414
+
415
+ sparse_embeddings, dense_embeddings = self.model.sam_prompt_encoder(
416
+ points=concat_points,
417
+ boxes=None,
418
+ masks=mask_input,
419
+ )
420
+
421
+ # Predict masks
422
+ batched_mode = (
423
+ concat_points is not None and concat_points[0].shape[0] > 1
424
+ ) # multi object prediction
425
+ high_res_features = [
426
+ feat_level[img_idx].unsqueeze(0)
427
+ for feat_level in self._features["high_res_feats"]
428
+ ]
429
+ low_res_masks, iou_predictions, _, _ = self.model.sam_mask_decoder(
430
+ image_embeddings=self._features["image_embed"][img_idx].unsqueeze(0),
431
+ image_pe=self.model.sam_prompt_encoder.get_dense_pe(),
432
+ sparse_prompt_embeddings=sparse_embeddings,
433
+ dense_prompt_embeddings=dense_embeddings,
434
+ multimask_output=multimask_output,
435
+ repeat_image=batched_mode,
436
+ high_res_features=high_res_features,
437
+ )
438
+
439
+ # Upscale the masks to the original image resolution
440
+ masks = self._transforms.postprocess_masks(
441
+ low_res_masks, self._orig_hw[img_idx]
442
+ )
443
+ low_res_masks = torch.clamp(low_res_masks, -32.0, 32.0)
444
+ if not return_logits:
445
+ masks = masks > self.mask_threshold
446
+
447
+ return masks, iou_predictions, low_res_masks
448
+
449
+ def get_image_embedding(self) -> torch.Tensor:
450
+ """
451
+ Returns the image embeddings for the currently set image, with
452
+ shape 1xCxHxW, where C is the embedding dimension and (H,W) are
453
+ the embedding spatial dimension of SAM (typically C=256, H=W=64).
454
+ """
455
+ if not self._is_image_set:
456
+ raise RuntimeError(
457
+ "An image must be set with .set_image(...) to generate an embedding."
458
+ )
459
+ assert (
460
+ self._features is not None
461
+ ), "Features must exist if an image has been set."
462
+ return self._features["image_embed"]
463
+
464
+ @property
465
+ def device(self) -> torch.device:
466
+ return self.model.device
467
+
468
+ def reset_predictor(self) -> None:
469
+ """
470
+ Resets the image embeddings and other state variables.
471
+ """
472
+ self._is_image_set = False
473
+ self._features = None
474
+ self._orig_hw = None
475
+ self._is_batch = False