nnInteractive 2.0.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 (76) hide show
  1. nnInteractive/__init__.py +3 -0
  2. nnInteractive/inference/__init__.py +0 -0
  3. nnInteractive/inference/cvpr2025_challenge_baseline/__init__.py +0 -0
  4. nnInteractive/inference/cvpr2025_challenge_baseline/predict.py +173 -0
  5. nnInteractive/inference/inference_session.py +1400 -0
  6. nnInteractive/interaction/__init__.py +0 -0
  7. nnInteractive/interaction/point.py +166 -0
  8. nnInteractive/supervoxel/setup.py +4 -0
  9. nnInteractive/supervoxel/src/metadata.py +118 -0
  10. nnInteractive/supervoxel/src/reader.py +175 -0
  11. nnInteractive/supervoxel/src/run.py +136 -0
  12. nnInteractive/supervoxel/src/sam2/__init__.py +2 -0
  13. nnInteractive/supervoxel/src/sam2/sam2/__init__.py +11 -0
  14. nnInteractive/supervoxel/src/sam2/sam2/automatic_mask_generator.py +434 -0
  15. nnInteractive/supervoxel/src/sam2/sam2/benchmark.py +86 -0
  16. nnInteractive/supervoxel/src/sam2/sam2/build_sam.py +172 -0
  17. nnInteractive/supervoxel/src/sam2/sam2/modeling/__init__.py +5 -0
  18. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/__init__.py +5 -0
  19. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/hieradet.py +305 -0
  20. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/image_encoder.py +132 -0
  21. nnInteractive/supervoxel/src/sam2/sam2/modeling/backbones/utils.py +89 -0
  22. nnInteractive/supervoxel/src/sam2/sam2/modeling/memory_attention.py +167 -0
  23. nnInteractive/supervoxel/src/sam2/sam2/modeling/memory_encoder.py +179 -0
  24. nnInteractive/supervoxel/src/sam2/sam2/modeling/position_encoding.py +217 -0
  25. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/__init__.py +5 -0
  26. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/mask_decoder.py +274 -0
  27. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/prompt_encoder.py +194 -0
  28. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam/transformer.py +293 -0
  29. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam2_base.py +879 -0
  30. nnInteractive/supervoxel/src/sam2/sam2/modeling/sam2_utils.py +315 -0
  31. nnInteractive/supervoxel/src/sam2/sam2/sam2_image_predictor.py +433 -0
  32. nnInteractive/supervoxel/src/sam2/sam2/sam2_video_predictor.py +1171 -0
  33. nnInteractive/supervoxel/src/sam2/sam2/sam2_video_predictor_legacy.py +1125 -0
  34. nnInteractive/supervoxel/src/sam2/sam2/utils/__init__.py +5 -0
  35. nnInteractive/supervoxel/src/sam2/sam2/utils/amg.py +332 -0
  36. nnInteractive/supervoxel/src/sam2/sam2/utils/misc.py +488 -0
  37. nnInteractive/supervoxel/src/sam2/sam2/utils/transforms.py +108 -0
  38. nnInteractive/supervoxel/src/sam2/setup.py +174 -0
  39. nnInteractive/supervoxel/src/sam2/training/__init__.py +5 -0
  40. nnInteractive/supervoxel/src/sam2/training/dataset/__init__.py +5 -0
  41. nnInteractive/supervoxel/src/sam2/training/dataset/sam2_datasets.py +176 -0
  42. nnInteractive/supervoxel/src/sam2/training/dataset/transforms.py +481 -0
  43. nnInteractive/supervoxel/src/sam2/training/dataset/utils.py +102 -0
  44. nnInteractive/supervoxel/src/sam2/training/dataset/vos_dataset.py +154 -0
  45. nnInteractive/supervoxel/src/sam2/training/dataset/vos_raw_dataset.py +290 -0
  46. nnInteractive/supervoxel/src/sam2/training/dataset/vos_sampler.py +103 -0
  47. nnInteractive/supervoxel/src/sam2/training/dataset/vos_segment_loader.py +289 -0
  48. nnInteractive/supervoxel/src/sam2/training/loss_fns.py +290 -0
  49. nnInteractive/supervoxel/src/sam2/training/model/__init__.py +5 -0
  50. nnInteractive/supervoxel/src/sam2/training/model/sam2.py +515 -0
  51. nnInteractive/supervoxel/src/sam2/training/optimizer.py +462 -0
  52. nnInteractive/supervoxel/src/sam2/training/scripts/sav_frame_extraction_submitit.py +157 -0
  53. nnInteractive/supervoxel/src/sam2/training/train.py +232 -0
  54. nnInteractive/supervoxel/src/sam2/training/trainer.py +1051 -0
  55. nnInteractive/supervoxel/src/sam2/training/utils/__init__.py +5 -0
  56. nnInteractive/supervoxel/src/sam2/training/utils/checkpoint_utils.py +328 -0
  57. nnInteractive/supervoxel/src/sam2/training/utils/data_utils.py +166 -0
  58. nnInteractive/supervoxel/src/sam2/training/utils/distributed.py +560 -0
  59. nnInteractive/supervoxel/src/sam2/training/utils/logger.py +236 -0
  60. nnInteractive/supervoxel/src/sam2/training/utils/train_utils.py +275 -0
  61. nnInteractive/supervoxel/src/supervoxel.py +198 -0
  62. nnInteractive/trainer/__init__.py +0 -0
  63. nnInteractive/trainer/nnInteractiveTrainer.py +24 -0
  64. nnInteractive/utils/__init__.py +0 -0
  65. nnInteractive/utils/bboxes.py +217 -0
  66. nnInteractive/utils/checkpoint_cleansing.py +9 -0
  67. nnInteractive/utils/crop.py +268 -0
  68. nnInteractive/utils/erosion_dilation.py +48 -0
  69. nnInteractive/utils/inference_helpers.py +45 -0
  70. nnInteractive/utils/os_shennanigans.py +16 -0
  71. nnInteractive/utils/rounding.py +13 -0
  72. nninteractive-2.0.0.dist-info/METADATA +511 -0
  73. nninteractive-2.0.0.dist-info/RECORD +76 -0
  74. nninteractive-2.0.0.dist-info/WHEEL +5 -0
  75. nninteractive-2.0.0.dist-info/licenses/LICENSE +201 -0
  76. nninteractive-2.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,433 @@
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
+
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
+ super().__init__()
43
+ self.model = sam_model
44
+ self._transforms = SAM2Transforms(
45
+ resolution=self.model.image_size,
46
+ mask_threshold=mask_threshold,
47
+ max_hole_area=max_hole_area,
48
+ max_sprinkle_area=max_sprinkle_area,
49
+ )
50
+
51
+ # Predictor state
52
+ self._is_image_set = False
53
+ self._features = None
54
+ self._orig_hw = None
55
+ # Whether the predictor is set for single image or a batch of images
56
+ self._is_batch = False
57
+
58
+ # Predictor config
59
+ self.mask_threshold = mask_threshold
60
+
61
+ # Spatial dim for backbone feature maps
62
+ self._bb_feat_sizes = [
63
+ (256, 256),
64
+ (128, 128),
65
+ (64, 64),
66
+ ]
67
+
68
+ @classmethod
69
+ def from_pretrained(cls, model_id: str, **kwargs) -> "SAM2ImagePredictor":
70
+ """
71
+ Load a pretrained model from the Hugging Face hub.
72
+
73
+ Arguments:
74
+ model_id (str): The Hugging Face repository ID.
75
+ **kwargs: Additional arguments to pass to the model constructor.
76
+
77
+ Returns:
78
+ (SAM2ImagePredictor): The loaded model.
79
+ """
80
+ from sam2.build_sam import build_sam2_hf
81
+
82
+ sam_model = build_sam2_hf(model_id, **kwargs)
83
+ return cls(sam_model, **kwargs)
84
+
85
+ @torch.no_grad()
86
+ def set_image(
87
+ self,
88
+ image: Union[np.ndarray, Image],
89
+ ) -> None:
90
+ """
91
+ Calculates the image embeddings for the provided image, allowing
92
+ masks to be predicted with the 'predict' method.
93
+
94
+ Arguments:
95
+ 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
96
+ with pixel values in [0, 255].
97
+ image_format (str): The color format of the image, in ['RGB', 'BGR'].
98
+ """
99
+ self.reset_predictor()
100
+ # Transform the image to the form expected by the model
101
+ if isinstance(image, np.ndarray):
102
+ logging.info("For numpy array image, we assume (HxWxC) format")
103
+ self._orig_hw = [image.shape[:2]]
104
+ elif isinstance(image, Image):
105
+ w, h = image.size
106
+ self._orig_hw = [(h, w)]
107
+ else:
108
+ raise NotImplementedError("Image format not supported")
109
+
110
+ input_image = self._transforms(image)
111
+ input_image = input_image[None, ...].to(self.device)
112
+
113
+ assert (
114
+ len(input_image.shape) == 4 and input_image.shape[1] == 3
115
+ ), f"input_image must be of size 1x3xHxW, got {input_image.shape}"
116
+ logging.info("Computing image embeddings for the provided image...")
117
+ backbone_out = self.model.forward_image(input_image)
118
+ _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out)
119
+ # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos
120
+ if self.model.directly_add_no_mem_embed:
121
+ vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
122
+
123
+ feats = [
124
+ feat.permute(1, 2, 0).view(1, -1, *feat_size)
125
+ for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1])
126
+ ][::-1]
127
+ self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
128
+ self._is_image_set = True
129
+ logging.info("Image embeddings computed.")
130
+
131
+ @torch.no_grad()
132
+ def set_image_batch(
133
+ self,
134
+ image_list: List[Union[np.ndarray]],
135
+ ) -> None:
136
+ """
137
+ Calculates the image embeddings for the provided image batch, allowing
138
+ masks to be predicted with the 'predict_batch' method.
139
+
140
+ Arguments:
141
+ image_list (List[np.ndarray]): The input images to embed in RGB format. The image should be in HWC format if np.ndarray
142
+ with pixel values in [0, 255].
143
+ """
144
+ self.reset_predictor()
145
+ assert isinstance(image_list, list)
146
+ self._orig_hw = []
147
+ for image in image_list:
148
+ assert isinstance(
149
+ image, np.ndarray
150
+ ), "Images are expected to be an np.ndarray in RGB format, and of shape HWC"
151
+ self._orig_hw.append(image.shape[:2])
152
+ # Transform the image to the form expected by the model
153
+ img_batch = self._transforms.forward_batch(image_list)
154
+ img_batch = img_batch.to(self.device)
155
+ batch_size = img_batch.shape[0]
156
+ assert (
157
+ len(img_batch.shape) == 4 and img_batch.shape[1] == 3
158
+ ), f"img_batch must be of size Bx3xHxW, got {img_batch.shape}"
159
+ logging.info("Computing image embeddings for the provided images...")
160
+ backbone_out = self.model.forward_image(img_batch)
161
+ _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out)
162
+ # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos
163
+ if self.model.directly_add_no_mem_embed:
164
+ vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
165
+
166
+ feats = [
167
+ feat.permute(1, 2, 0).view(batch_size, -1, *feat_size)
168
+ for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1])
169
+ ][::-1]
170
+ self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
171
+ self._is_image_set = True
172
+ self._is_batch = True
173
+ logging.info("Image embeddings computed.")
174
+
175
+ def predict_batch(
176
+ self,
177
+ point_coords_batch: List[np.ndarray] = None,
178
+ point_labels_batch: List[np.ndarray] = None,
179
+ box_batch: List[np.ndarray] = None,
180
+ mask_input_batch: List[np.ndarray] = None,
181
+ multimask_output: bool = True,
182
+ return_logits: bool = False,
183
+ normalize_coords=True,
184
+ ) -> Tuple[List[np.ndarray], List[np.ndarray], List[np.ndarray]]:
185
+ """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.
186
+ It returns a tuple of lists of masks, ious, and low_res_masks_logits.
187
+ """
188
+ assert self._is_batch, "This function should only be used when in batched mode"
189
+ if not self._is_image_set:
190
+ raise RuntimeError("An image must be set with .set_image_batch(...) before mask prediction.")
191
+ num_images = len(self._features["image_embed"])
192
+ all_masks = []
193
+ all_ious = []
194
+ all_low_res_masks = []
195
+ for img_idx in range(num_images):
196
+ # Transform input prompts
197
+ point_coords = point_coords_batch[img_idx] if point_coords_batch is not None else None
198
+ point_labels = point_labels_batch[img_idx] if point_labels_batch is not None else None
199
+ box = box_batch[img_idx] if box_batch is not None else None
200
+ mask_input = mask_input_batch[img_idx] if mask_input_batch is not None else None
201
+ mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts(
202
+ point_coords,
203
+ point_labels,
204
+ box,
205
+ mask_input,
206
+ normalize_coords,
207
+ img_idx=img_idx,
208
+ )
209
+ masks, iou_predictions, low_res_masks = self._predict(
210
+ unnorm_coords,
211
+ labels,
212
+ unnorm_box,
213
+ mask_input,
214
+ multimask_output,
215
+ return_logits=return_logits,
216
+ img_idx=img_idx,
217
+ )
218
+ masks_np = masks.squeeze(0).float().detach().cpu().numpy()
219
+ iou_predictions_np = iou_predictions.squeeze(0).float().detach().cpu().numpy()
220
+ low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy()
221
+ all_masks.append(masks_np)
222
+ all_ious.append(iou_predictions_np)
223
+ all_low_res_masks.append(low_res_masks_np)
224
+
225
+ return all_masks, all_ious, all_low_res_masks
226
+
227
+ def predict(
228
+ self,
229
+ point_coords: Optional[np.ndarray] = None,
230
+ point_labels: Optional[np.ndarray] = None,
231
+ box: Optional[np.ndarray] = None,
232
+ mask_input: Optional[np.ndarray] = None,
233
+ multimask_output: bool = True,
234
+ return_logits: bool = False,
235
+ normalize_coords=True,
236
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
237
+ """
238
+ Predict masks for the given input prompts, using the currently set image.
239
+
240
+ Arguments:
241
+ point_coords (np.ndarray or None): A Nx2 array of point prompts to the
242
+ model. Each point is in (X,Y) in pixels.
243
+ point_labels (np.ndarray or None): A length N array of labels for the
244
+ point prompts. 1 indicates a foreground point and 0 indicates a
245
+ background point.
246
+ box (np.ndarray or None): A length 4 array given a box prompt to the
247
+ model, in XYXY format.
248
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
249
+ coming from a previous prediction iteration. Has form 1xHxW, where
250
+ for SAM, H=W=256.
251
+ multimask_output (bool): If true, the model will return three masks.
252
+ For ambiguous input prompts (such as a single click), this will often
253
+ produce better masks than a single prediction. If only a single
254
+ mask is needed, the model's predicted quality score can be used
255
+ to select the best mask. For non-ambiguous prompts, such as multiple
256
+ input prompts, multimask_output=False can give better results.
257
+ return_logits (bool): If true, returns un-thresholded masks logits
258
+ instead of a binary mask.
259
+ 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.
260
+
261
+ Returns:
262
+ (np.ndarray): The output masks in CxHxW format, where C is the
263
+ number of masks, and (H, W) is the original image size.
264
+ (np.ndarray): An array of length C containing the model's
265
+ predictions for the quality of each mask.
266
+ (np.ndarray): An array of shape CxHxW, where C is the number
267
+ of masks and H=W=256. These low resolution logits can be passed to
268
+ a subsequent iteration as mask input.
269
+ """
270
+ if not self._is_image_set:
271
+ raise RuntimeError("An image must be set with .set_image(...) before mask prediction.")
272
+
273
+ # Transform input prompts
274
+
275
+ mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts(
276
+ point_coords, point_labels, box, mask_input, normalize_coords
277
+ )
278
+
279
+ masks, iou_predictions, low_res_masks = self._predict(
280
+ unnorm_coords,
281
+ labels,
282
+ unnorm_box,
283
+ mask_input,
284
+ multimask_output,
285
+ return_logits=return_logits,
286
+ )
287
+
288
+ masks_np = masks.squeeze(0).float().detach().cpu().numpy()
289
+ iou_predictions_np = iou_predictions.squeeze(0).float().detach().cpu().numpy()
290
+ low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy()
291
+ return masks_np, iou_predictions_np, low_res_masks_np
292
+
293
+ def _prep_prompts(self, point_coords, point_labels, box, mask_logits, normalize_coords, img_idx=-1):
294
+
295
+ unnorm_coords, labels, unnorm_box, mask_input = None, None, None, None
296
+ if point_coords is not None:
297
+ assert point_labels is not None, "point_labels must be supplied if point_coords is supplied."
298
+ point_coords = torch.as_tensor(point_coords, dtype=torch.float, device=self.device)
299
+ unnorm_coords = self._transforms.transform_coords(
300
+ point_coords, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx]
301
+ )
302
+ labels = torch.as_tensor(point_labels, dtype=torch.int, device=self.device)
303
+ if len(unnorm_coords.shape) == 2:
304
+ unnorm_coords, labels = unnorm_coords[None, ...], labels[None, ...]
305
+ if box is not None:
306
+ box = torch.as_tensor(box, dtype=torch.float, device=self.device)
307
+ unnorm_box = self._transforms.transform_boxes(
308
+ box, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx]
309
+ ) # Bx2x2
310
+ if mask_logits is not None:
311
+ mask_input = torch.as_tensor(mask_logits, dtype=torch.float, device=self.device)
312
+ if len(mask_input.shape) == 3:
313
+ mask_input = mask_input[None, :, :, :]
314
+ return mask_input, unnorm_coords, labels, unnorm_box
315
+
316
+ @torch.no_grad()
317
+ def _predict(
318
+ self,
319
+ point_coords: Optional[torch.Tensor],
320
+ point_labels: Optional[torch.Tensor],
321
+ boxes: Optional[torch.Tensor] = None,
322
+ mask_input: Optional[torch.Tensor] = None,
323
+ multimask_output: bool = True,
324
+ return_logits: bool = False,
325
+ img_idx: int = -1,
326
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
327
+ """
328
+ Predict masks for the given input prompts, using the currently set image.
329
+ Input prompts are batched torch tensors and are expected to already be
330
+ transformed to the input frame using SAM2Transforms.
331
+
332
+ Arguments:
333
+ point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the
334
+ model. Each point is in (X,Y) in pixels.
335
+ point_labels (torch.Tensor or None): A BxN array of labels for the
336
+ point prompts. 1 indicates a foreground point and 0 indicates a
337
+ background point.
338
+ boxes (np.ndarray or None): A Bx4 array given a box prompt to the
339
+ model, in XYXY format.
340
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
341
+ coming from a previous prediction iteration. Has form Bx1xHxW, where
342
+ for SAM, H=W=256. Masks returned by a previous iteration of the
343
+ predict method do not need further transformation.
344
+ multimask_output (bool): If true, the model will return three masks.
345
+ For ambiguous input prompts (such as a single click), this will often
346
+ produce better masks than a single prediction. If only a single
347
+ mask is needed, the model's predicted quality score can be used
348
+ to select the best mask. For non-ambiguous prompts, such as multiple
349
+ input prompts, multimask_output=False can give better results.
350
+ return_logits (bool): If true, returns un-thresholded masks logits
351
+ instead of a binary mask.
352
+
353
+ Returns:
354
+ (torch.Tensor): The output masks in BxCxHxW format, where C is the
355
+ number of masks, and (H, W) is the original image size.
356
+ (torch.Tensor): An array of shape BxC containing the model's
357
+ predictions for the quality of each mask.
358
+ (torch.Tensor): An array of shape BxCxHxW, where C is the number
359
+ of masks and H=W=256. These low res logits can be passed to
360
+ a subsequent iteration as mask input.
361
+ """
362
+ if not self._is_image_set:
363
+ raise RuntimeError("An image must be set with .set_image(...) before mask prediction.")
364
+
365
+ if point_coords is not None:
366
+ concat_points = (point_coords, point_labels)
367
+ else:
368
+ concat_points = None
369
+
370
+ # Embed prompts
371
+ if boxes is not None:
372
+ box_coords = boxes.reshape(-1, 2, 2)
373
+ box_labels = torch.tensor([[2, 3]], dtype=torch.int, device=boxes.device)
374
+ box_labels = box_labels.repeat(boxes.size(0), 1)
375
+ # we merge "boxes" and "points" into a single "concat_points" input (where
376
+ # boxes are added at the beginning) to sam_prompt_encoder
377
+ if concat_points is not None:
378
+ concat_coords = torch.cat([box_coords, concat_points[0]], dim=1)
379
+ concat_labels = torch.cat([box_labels, concat_points[1]], dim=1)
380
+ concat_points = (concat_coords, concat_labels)
381
+ else:
382
+ concat_points = (box_coords, box_labels)
383
+
384
+ sparse_embeddings, dense_embeddings = self.model.sam_prompt_encoder(
385
+ points=concat_points,
386
+ boxes=None,
387
+ masks=mask_input,
388
+ )
389
+
390
+ # Predict masks
391
+ batched_mode = concat_points is not None and concat_points[0].shape[0] > 1 # multi object prediction
392
+ high_res_features = [feat_level[img_idx].unsqueeze(0) for feat_level in self._features["high_res_feats"]]
393
+ low_res_masks, iou_predictions, _, _ = self.model.sam_mask_decoder(
394
+ image_embeddings=self._features["image_embed"][img_idx].unsqueeze(0),
395
+ image_pe=self.model.sam_prompt_encoder.get_dense_pe(),
396
+ sparse_prompt_embeddings=sparse_embeddings,
397
+ dense_prompt_embeddings=dense_embeddings,
398
+ multimask_output=multimask_output,
399
+ repeat_image=batched_mode,
400
+ high_res_features=high_res_features,
401
+ )
402
+
403
+ # Upscale the masks to the original image resolution
404
+ masks = self._transforms.postprocess_masks(low_res_masks, self._orig_hw[img_idx])
405
+ low_res_masks = torch.clamp(low_res_masks, -32.0, 32.0)
406
+ if not return_logits:
407
+ masks = masks > self.mask_threshold
408
+
409
+ return masks, iou_predictions, low_res_masks
410
+
411
+ def get_image_embedding(self) -> torch.Tensor:
412
+ """
413
+ Returns the image embeddings for the currently set image, with
414
+ shape 1xCxHxW, where C is the embedding dimension and (H,W) are
415
+ the embedding spatial dimension of SAM (typically C=256, H=W=64).
416
+ """
417
+ if not self._is_image_set:
418
+ raise RuntimeError("An image must be set with .set_image(...) to generate an embedding.")
419
+ assert self._features is not None, "Features must exist if an image has been set."
420
+ return self._features["image_embed"]
421
+
422
+ @property
423
+ def device(self) -> torch.device:
424
+ return self.model.device
425
+
426
+ def reset_predictor(self) -> None:
427
+ """
428
+ Resets the image embeddings and other state variables.
429
+ """
430
+ self._is_image_set = False
431
+ self._features = None
432
+ self._orig_hw = None
433
+ self._is_batch = False