predict.py 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. """
  3. Generate predictions using the Segment Anything Model (SAM).
  4. SAM is an advanced image segmentation model offering features like promptable segmentation and zero-shot performance.
  5. This module contains the implementation of the prediction logic and auxiliary utilities required to perform segmentation
  6. using SAM. It forms an integral part of the Ultralytics framework and is designed for high-performance, real-time image
  7. segmentation tasks.
  8. """
  9. from collections import OrderedDict
  10. import numpy as np
  11. import torch
  12. import torch.nn.functional as F
  13. from ultralytics.data.augment import LetterBox
  14. from ultralytics.engine.predictor import BasePredictor
  15. from ultralytics.engine.results import Results
  16. from ultralytics.utils import DEFAULT_CFG, ops
  17. from ultralytics.utils.torch_utils import select_device, smart_inference_mode
  18. from .amg import (
  19. batch_iterator,
  20. batched_mask_to_box,
  21. build_all_layer_point_grids,
  22. calculate_stability_score,
  23. generate_crop_boxes,
  24. is_box_near_crop_edge,
  25. remove_small_regions,
  26. uncrop_boxes_xyxy,
  27. uncrop_masks,
  28. )
  29. from .build import build_sam
  30. class Predictor(BasePredictor):
  31. """
  32. Predictor class for SAM, enabling real-time image segmentation with promptable capabilities.
  33. This class extends BasePredictor and implements the Segment Anything Model (SAM) for advanced image
  34. segmentation tasks. It supports various input prompts like points, bounding boxes, and masks for
  35. fine-grained control over segmentation results.
  36. Attributes:
  37. args (SimpleNamespace): Configuration arguments for the predictor.
  38. model (torch.nn.Module): The loaded SAM model.
  39. device (torch.device): The device (CPU or GPU) on which the model is loaded.
  40. im (torch.Tensor): The preprocessed input image.
  41. features (torch.Tensor): Extracted image features.
  42. prompts (Dict): Dictionary to store various types of prompts (e.g., bboxes, points, masks).
  43. segment_all (bool): Flag to indicate if full image segmentation should be performed.
  44. mean (torch.Tensor): Mean values for image normalization.
  45. std (torch.Tensor): Standard deviation values for image normalization.
  46. Methods:
  47. preprocess: Prepares input images for model inference.
  48. pre_transform: Performs initial transformations on the input image.
  49. inference: Performs segmentation inference based on input prompts.
  50. prompt_inference: Internal function for prompt-based segmentation inference.
  51. generate: Generates segmentation masks for an entire image.
  52. setup_model: Initializes the SAM model for inference.
  53. get_model: Builds and returns a SAM model.
  54. postprocess: Post-processes model outputs to generate final results.
  55. setup_source: Sets up the data source for inference.
  56. set_image: Sets and preprocesses a single image for inference.
  57. get_im_features: Extracts image features using the SAM image encoder.
  58. set_prompts: Sets prompts for subsequent inference.
  59. reset_image: Resets the current image and its features.
  60. remove_small_regions: Removes small disconnected regions and holes from masks.
  61. Examples:
  62. >>> predictor = Predictor()
  63. >>> predictor.setup_model(model_path="sam_model.pt")
  64. >>> predictor.set_image("image.jpg")
  65. >>> bboxes = [[100, 100, 200, 200]]
  66. >>> results = predictor(bboxes=bboxes)
  67. """
  68. def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
  69. """
  70. Initialize the Predictor with configuration, overrides, and callbacks.
  71. Sets up the Predictor object for SAM (Segment Anything Model) and applies any configuration overrides or
  72. callbacks provided. Initializes task-specific settings for SAM, such as retina_masks being set to True
  73. for optimal results.
  74. Args:
  75. cfg (Dict): Configuration dictionary containing default settings.
  76. overrides (Dict | None): Dictionary of values to override default configuration.
  77. _callbacks (Dict | None): Dictionary of callback functions to customize behavior.
  78. Examples:
  79. >>> predictor_example = Predictor(cfg=DEFAULT_CFG)
  80. >>> predictor_example_with_imgsz = Predictor(overrides={"imgsz": 640})
  81. >>> predictor_example_with_callback = Predictor(_callbacks={"on_predict_start": custom_callback})
  82. """
  83. if overrides is None:
  84. overrides = {}
  85. overrides.update(dict(task="segment", mode="predict", batch=1))
  86. super().__init__(cfg, overrides, _callbacks)
  87. self.args.retina_masks = True
  88. self.im = None
  89. self.features = None
  90. self.prompts = {}
  91. self.segment_all = False
  92. def preprocess(self, im):
  93. """
  94. Preprocess the input image for model inference.
  95. This method prepares the input image by applying transformations and normalization. It supports both
  96. torch.Tensor and list of np.ndarray as input formats.
  97. Args:
  98. im (torch.Tensor | List[np.ndarray]): Input image(s) in BCHW tensor format or list of HWC numpy arrays.
  99. Returns:
  100. im (torch.Tensor): The preprocessed image tensor, normalized and converted to the appropriate dtype.
  101. Examples:
  102. >>> predictor = Predictor()
  103. >>> image = torch.rand(1, 3, 640, 640)
  104. >>> preprocessed_image = predictor.preprocess(image)
  105. """
  106. if self.im is not None:
  107. return self.im
  108. not_tensor = not isinstance(im, torch.Tensor)
  109. if not_tensor:
  110. im = np.stack(self.pre_transform(im))
  111. im = im[..., ::-1].transpose((0, 3, 1, 2))
  112. im = np.ascontiguousarray(im)
  113. im = torch.from_numpy(im)
  114. im = im.to(self.device)
  115. im = im.half() if self.model.fp16 else im.float()
  116. if not_tensor:
  117. im = (im - self.mean) / self.std
  118. return im
  119. def pre_transform(self, im):
  120. """
  121. Perform initial transformations on the input image for preprocessing.
  122. This method applies transformations such as resizing to prepare the image for further preprocessing.
  123. Currently, batched inference is not supported; hence the list length should be 1.
  124. Args:
  125. im (List[np.ndarray]): List containing a single image in HWC numpy array format.
  126. Returns:
  127. (List[np.ndarray]): List containing the transformed image.
  128. Raises:
  129. AssertionError: If the input list contains more than one image.
  130. Examples:
  131. >>> predictor = Predictor()
  132. >>> image = np.random.rand(480, 640, 3) # Single HWC image
  133. >>> transformed = predictor.pre_transform([image])
  134. >>> print(len(transformed))
  135. 1
  136. """
  137. assert len(im) == 1, "SAM model does not currently support batched inference"
  138. letterbox = LetterBox(self.args.imgsz, auto=False, center=False)
  139. return [letterbox(image=x) for x in im]
  140. def inference(self, im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False, *args, **kwargs):
  141. """
  142. Perform image segmentation inference based on the given input cues, using the currently loaded image.
  143. This method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt
  144. encoder, and mask decoder for real-time and promptable segmentation tasks.
  145. Args:
  146. im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
  147. bboxes (np.ndarray | List | None): Bounding boxes with shape (N, 4), in XYXY format.
  148. points (np.ndarray | List | None): Points indicating object locations with shape (N, 2), in pixels.
  149. labels (np.ndarray | List | None): Labels for point prompts, shape (N,). 1 = foreground, 0 = background.
  150. masks (np.ndarray | None): Low-resolution masks from previous predictions, shape (N, H, W). For SAM H=W=256.
  151. multimask_output (bool): Flag to return multiple masks. Helpful for ambiguous prompts.
  152. *args (Any): Additional positional arguments.
  153. **kwargs (Any): Additional keyword arguments.
  154. Returns:
  155. (np.ndarray): The output masks in shape (C, H, W), where C is the number of generated masks.
  156. (np.ndarray): An array of length C containing quality scores predicted by the model for each mask.
  157. (np.ndarray): Low-resolution logits of shape (C, H, W) for subsequent inference, where H=W=256.
  158. Examples:
  159. >>> predictor = Predictor()
  160. >>> predictor.setup_model(model_path="sam_model.pt")
  161. >>> predictor.set_image("image.jpg")
  162. >>> results = predictor(bboxes=[[0, 0, 100, 100]])
  163. """
  164. # Override prompts if any stored in self.prompts
  165. bboxes = self.prompts.pop("bboxes", bboxes)
  166. points = self.prompts.pop("points", points)
  167. masks = self.prompts.pop("masks", masks)
  168. labels = self.prompts.pop("labels", labels)
  169. if all(i is None for i in [bboxes, points, masks]):
  170. return self.generate(im, *args, **kwargs)
  171. return self.prompt_inference(im, bboxes, points, labels, masks, multimask_output)
  172. def prompt_inference(self, im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False):
  173. """
  174. Performs image segmentation inference based on input cues using SAM's specialized architecture.
  175. This internal function leverages the Segment Anything Model (SAM) for prompt-based, real-time segmentation.
  176. It processes various input prompts such as bounding boxes, points, and masks to generate segmentation masks.
  177. Args:
  178. im (torch.Tensor): Preprocessed input image tensor with shape (N, C, H, W).
  179. bboxes (np.ndarray | List | None): Bounding boxes in XYXY format with shape (N, 4).
  180. points (np.ndarray | List | None): Points indicating object locations with shape (N, 2) or (N, num_points, 2), in pixels.
  181. labels (np.ndarray | List | None): Point prompt labels with shape (N) or (N, num_points). 1 for foreground, 0 for background.
  182. masks (np.ndarray | None): Low-res masks from previous predictions with shape (N, H, W). For SAM, H=W=256.
  183. multimask_output (bool): Flag to return multiple masks for ambiguous prompts.
  184. Raises:
  185. AssertionError: If the number of points don't match the number of labels, in case labels were passed.
  186. Returns:
  187. (np.ndarray): Output masks with shape (C, H, W), where C is the number of generated masks.
  188. (np.ndarray): Quality scores predicted by the model for each mask, with length C.
  189. Examples:
  190. >>> predictor = Predictor()
  191. >>> im = torch.rand(1, 3, 1024, 1024)
  192. >>> bboxes = [[100, 100, 200, 200]]
  193. >>> masks, scores, logits = predictor.prompt_inference(im, bboxes=bboxes)
  194. """
  195. features = self.get_im_features(im) if self.features is None else self.features
  196. bboxes, points, labels, masks = self._prepare_prompts(im.shape[2:], bboxes, points, labels, masks)
  197. points = (points, labels) if points is not None else None
  198. # Embed prompts
  199. sparse_embeddings, dense_embeddings = self.model.prompt_encoder(points=points, boxes=bboxes, masks=masks)
  200. # Predict masks
  201. pred_masks, pred_scores = self.model.mask_decoder(
  202. image_embeddings=features,
  203. image_pe=self.model.prompt_encoder.get_dense_pe(),
  204. sparse_prompt_embeddings=sparse_embeddings,
  205. dense_prompt_embeddings=dense_embeddings,
  206. multimask_output=multimask_output,
  207. )
  208. # (N, d, H, W) --> (N*d, H, W), (N, d) --> (N*d, )
  209. # `d` could be 1 or 3 depends on `multimask_output`.
  210. return pred_masks.flatten(0, 1), pred_scores.flatten(0, 1)
  211. def _prepare_prompts(self, dst_shape, bboxes=None, points=None, labels=None, masks=None):
  212. """
  213. Prepares and transforms the input prompts for processing based on the destination shape.
  214. Args:
  215. dst_shape (tuple): The target shape (height, width) for the prompts.
  216. bboxes (np.ndarray | List | None): Bounding boxes in XYXY format with shape (N, 4).
  217. points (np.ndarray | List | None): Points indicating object locations with shape (N, 2) or (N, num_points, 2), in pixels.
  218. labels (np.ndarray | List | None): Point prompt labels with shape (N) or (N, num_points). 1 for foreground, 0 for background.
  219. masks (List | np.ndarray, Optional): Masks for the objects, where each mask is a 2D array.
  220. Raises:
  221. AssertionError: If the number of points don't match the number of labels, in case labels were passed.
  222. Returns:
  223. (tuple): A tuple containing transformed bounding boxes, points, labels, and masks.
  224. """
  225. src_shape = self.batch[1][0].shape[:2]
  226. r = 1.0 if self.segment_all else min(dst_shape[0] / src_shape[0], dst_shape[1] / src_shape[1])
  227. # Transform input prompts
  228. if points is not None:
  229. points = torch.as_tensor(points, dtype=torch.float32, device=self.device)
  230. points = points[None] if points.ndim == 1 else points
  231. # Assuming labels are all positive if users don't pass labels.
  232. if labels is None:
  233. labels = np.ones(points.shape[:-1])
  234. labels = torch.as_tensor(labels, dtype=torch.int32, device=self.device)
  235. assert points.shape[-2] == labels.shape[-1], (
  236. f"Number of points {points.shape[-2]} should match number of labels {labels.shape[-1]}."
  237. )
  238. points *= r
  239. if points.ndim == 2:
  240. # (N, 2) --> (N, 1, 2), (N, ) --> (N, 1)
  241. points, labels = points[:, None, :], labels[:, None]
  242. if bboxes is not None:
  243. bboxes = torch.as_tensor(bboxes, dtype=torch.float32, device=self.device)
  244. bboxes = bboxes[None] if bboxes.ndim == 1 else bboxes
  245. bboxes *= r
  246. if masks is not None:
  247. masks = torch.as_tensor(masks, dtype=torch.float32, device=self.device).unsqueeze(1)
  248. return bboxes, points, labels, masks
  249. def generate(
  250. self,
  251. im,
  252. crop_n_layers=0,
  253. crop_overlap_ratio=512 / 1500,
  254. crop_downscale_factor=1,
  255. point_grids=None,
  256. points_stride=32,
  257. points_batch_size=64,
  258. conf_thres=0.88,
  259. stability_score_thresh=0.95,
  260. stability_score_offset=0.95,
  261. crop_nms_thresh=0.7,
  262. ):
  263. """
  264. Perform image segmentation using the Segment Anything Model (SAM).
  265. This method segments an entire image into constituent parts by leveraging SAM's advanced architecture
  266. and real-time performance capabilities. It can optionally work on image crops for finer segmentation.
  267. Args:
  268. im (torch.Tensor): Input tensor representing the preprocessed image with shape (N, C, H, W).
  269. crop_n_layers (int): Number of layers for additional mask predictions on image crops.
  270. crop_overlap_ratio (float): Overlap between crops, scaled down in subsequent layers.
  271. crop_downscale_factor (int): Scaling factor for sampled points-per-side in each layer.
  272. point_grids (List[np.ndarray] | None): Custom grids for point sampling normalized to [0,1].
  273. points_stride (int): Number of points to sample along each side of the image.
  274. points_batch_size (int): Batch size for the number of points processed simultaneously.
  275. conf_thres (float): Confidence threshold [0,1] for filtering based on mask quality prediction.
  276. stability_score_thresh (float): Stability threshold [0,1] for mask filtering based on stability.
  277. stability_score_offset (float): Offset value for calculating stability score.
  278. crop_nms_thresh (float): IoU cutoff for NMS to remove duplicate masks between crops.
  279. Returns:
  280. pred_masks (torch.Tensor): Segmented masks with shape (N, H, W).
  281. pred_scores (torch.Tensor): Confidence scores for each mask with shape (N,).
  282. pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 4).
  283. Examples:
  284. >>> predictor = Predictor()
  285. >>> im = torch.rand(1, 3, 1024, 1024) # Example input image
  286. >>> masks, scores, boxes = predictor.generate(im)
  287. """
  288. import torchvision # scope for faster 'import ultralytics'
  289. self.segment_all = True
  290. ih, iw = im.shape[2:]
  291. crop_regions, layer_idxs = generate_crop_boxes((ih, iw), crop_n_layers, crop_overlap_ratio)
  292. if point_grids is None:
  293. point_grids = build_all_layer_point_grids(points_stride, crop_n_layers, crop_downscale_factor)
  294. pred_masks, pred_scores, pred_bboxes, region_areas = [], [], [], []
  295. for crop_region, layer_idx in zip(crop_regions, layer_idxs):
  296. x1, y1, x2, y2 = crop_region
  297. w, h = x2 - x1, y2 - y1
  298. area = torch.tensor(w * h, device=im.device)
  299. points_scale = np.array([[w, h]]) # w, h
  300. # Crop image and interpolate to input size
  301. crop_im = F.interpolate(im[..., y1:y2, x1:x2], (ih, iw), mode="bilinear", align_corners=False)
  302. # (num_points, 2)
  303. points_for_image = point_grids[layer_idx] * points_scale
  304. crop_masks, crop_scores, crop_bboxes = [], [], []
  305. for (points,) in batch_iterator(points_batch_size, points_for_image):
  306. pred_mask, pred_score = self.prompt_inference(crop_im, points=points, multimask_output=True)
  307. # Interpolate predicted masks to input size
  308. pred_mask = F.interpolate(pred_mask[None], (h, w), mode="bilinear", align_corners=False)[0]
  309. idx = pred_score > conf_thres
  310. pred_mask, pred_score = pred_mask[idx], pred_score[idx]
  311. stability_score = calculate_stability_score(
  312. pred_mask, self.model.mask_threshold, stability_score_offset
  313. )
  314. idx = stability_score > stability_score_thresh
  315. pred_mask, pred_score = pred_mask[idx], pred_score[idx]
  316. # Bool type is much more memory-efficient.
  317. pred_mask = pred_mask > self.model.mask_threshold
  318. # (N, 4)
  319. pred_bbox = batched_mask_to_box(pred_mask).float()
  320. keep_mask = ~is_box_near_crop_edge(pred_bbox, crop_region, [0, 0, iw, ih])
  321. if not torch.all(keep_mask):
  322. pred_bbox, pred_mask, pred_score = pred_bbox[keep_mask], pred_mask[keep_mask], pred_score[keep_mask]
  323. crop_masks.append(pred_mask)
  324. crop_bboxes.append(pred_bbox)
  325. crop_scores.append(pred_score)
  326. # Do nms within this crop
  327. crop_masks = torch.cat(crop_masks)
  328. crop_bboxes = torch.cat(crop_bboxes)
  329. crop_scores = torch.cat(crop_scores)
  330. keep = torchvision.ops.nms(crop_bboxes, crop_scores, self.args.iou) # NMS
  331. crop_bboxes = uncrop_boxes_xyxy(crop_bboxes[keep], crop_region)
  332. crop_masks = uncrop_masks(crop_masks[keep], crop_region, ih, iw)
  333. crop_scores = crop_scores[keep]
  334. pred_masks.append(crop_masks)
  335. pred_bboxes.append(crop_bboxes)
  336. pred_scores.append(crop_scores)
  337. region_areas.append(area.expand(len(crop_masks)))
  338. pred_masks = torch.cat(pred_masks)
  339. pred_bboxes = torch.cat(pred_bboxes)
  340. pred_scores = torch.cat(pred_scores)
  341. region_areas = torch.cat(region_areas)
  342. # Remove duplicate masks between crops
  343. if len(crop_regions) > 1:
  344. scores = 1 / region_areas
  345. keep = torchvision.ops.nms(pred_bboxes, scores, crop_nms_thresh)
  346. pred_masks, pred_bboxes, pred_scores = pred_masks[keep], pred_bboxes[keep], pred_scores[keep]
  347. return pred_masks, pred_scores, pred_bboxes
  348. def setup_model(self, model=None, verbose=True):
  349. """
  350. Initializes the Segment Anything Model (SAM) for inference.
  351. This method sets up the SAM model by allocating it to the appropriate device and initializing the necessary
  352. parameters for image normalization and other Ultralytics compatibility settings.
  353. Args:
  354. model (torch.nn.Module | None): A pretrained SAM model. If None, a new model is built based on config.
  355. verbose (bool): If True, prints selected device information.
  356. Examples:
  357. >>> predictor = Predictor()
  358. >>> predictor.setup_model(model=sam_model, verbose=True)
  359. """
  360. device = select_device(self.args.device, verbose=verbose)
  361. if model is None:
  362. model = self.get_model()
  363. model.eval()
  364. self.model = model.to(device)
  365. self.device = device
  366. self.mean = torch.tensor([123.675, 116.28, 103.53]).view(-1, 1, 1).to(device)
  367. self.std = torch.tensor([58.395, 57.12, 57.375]).view(-1, 1, 1).to(device)
  368. # Ultralytics compatibility settings
  369. self.model.pt = False
  370. self.model.triton = False
  371. self.model.stride = 32
  372. self.model.fp16 = False
  373. self.done_warmup = True
  374. def get_model(self):
  375. """Retrieves or builds the Segment Anything Model (SAM) for image segmentation tasks."""
  376. return build_sam(self.args.model)
  377. def postprocess(self, preds, img, orig_imgs):
  378. """
  379. Post-processes SAM's inference outputs to generate object detection masks and bounding boxes.
  380. This method scales masks and boxes to the original image size and applies a threshold to the mask
  381. predictions. It leverages SAM's advanced architecture for real-time, promptable segmentation tasks.
  382. Args:
  383. preds (Tuple[torch.Tensor]): The output from SAM model inference, containing:
  384. - pred_masks (torch.Tensor): Predicted masks with shape (N, 1, H, W).
  385. - pred_scores (torch.Tensor): Confidence scores for each mask with shape (N, 1).
  386. - pred_bboxes (torch.Tensor, optional): Predicted bounding boxes if segment_all is True.
  387. img (torch.Tensor): The processed input image tensor with shape (C, H, W).
  388. orig_imgs (List[np.ndarray] | torch.Tensor): The original, unprocessed images.
  389. Returns:
  390. results (List[Results]): List of Results objects containing detection masks, bounding boxes, and other
  391. metadata for each processed image.
  392. Examples:
  393. >>> predictor = Predictor()
  394. >>> preds = predictor.inference(img)
  395. >>> results = predictor.postprocess(preds, img, orig_imgs)
  396. """
  397. # (N, 1, H, W), (N, 1)
  398. pred_masks, pred_scores = preds[:2]
  399. pred_bboxes = preds[2] if self.segment_all else None
  400. names = dict(enumerate(str(i) for i in range(len(pred_masks))))
  401. if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list
  402. orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)
  403. results = []
  404. for masks, orig_img, img_path in zip([pred_masks], orig_imgs, self.batch[0]):
  405. if len(masks) == 0:
  406. masks, pred_bboxes = None, torch.zeros((0, 6), device=pred_masks.device)
  407. else:
  408. masks = ops.scale_masks(masks[None].float(), orig_img.shape[:2], padding=False)[0]
  409. masks = masks > self.model.mask_threshold # to bool
  410. if pred_bboxes is not None:
  411. pred_bboxes = ops.scale_boxes(img.shape[2:], pred_bboxes.float(), orig_img.shape, padding=False)
  412. else:
  413. pred_bboxes = batched_mask_to_box(masks)
  414. # NOTE: SAM models do not return cls info. This `cls` here is just a placeholder for consistency.
  415. cls = torch.arange(len(pred_masks), dtype=torch.int32, device=pred_masks.device)
  416. pred_bboxes = torch.cat([pred_bboxes, pred_scores[:, None], cls[:, None]], dim=-1)
  417. results.append(Results(orig_img, path=img_path, names=names, masks=masks, boxes=pred_bboxes))
  418. # Reset segment-all mode.
  419. self.segment_all = False
  420. return results
  421. def setup_source(self, source):
  422. """
  423. Sets up the data source for inference.
  424. This method configures the data source from which images will be fetched for inference. It supports
  425. various input types such as image files, directories, video files, and other compatible data sources.
  426. Args:
  427. source (str | Path | None): The path or identifier for the image data source. Can be a file path,
  428. directory path, URL, or other supported source types.
  429. Examples:
  430. >>> predictor = Predictor()
  431. >>> predictor.setup_source("path/to/images")
  432. >>> predictor.setup_source("video.mp4")
  433. >>> predictor.setup_source(None) # Uses default source if available
  434. Notes:
  435. - If source is None, the method may use a default source if configured.
  436. - The method adapts to different source types and prepares them for subsequent inference steps.
  437. - Supported source types may include local files, directories, URLs, and video streams.
  438. """
  439. if source is not None:
  440. super().setup_source(source)
  441. def set_image(self, image):
  442. """
  443. Preprocesses and sets a single image for inference.
  444. This method prepares the model for inference on a single image by setting up the model if not already
  445. initialized, configuring the data source, and preprocessing the image for feature extraction. It
  446. ensures that only one image is set at a time and extracts image features for subsequent use.
  447. Args:
  448. image (str | np.ndarray): Path to the image file as a string, or a numpy array representing
  449. an image read by cv2.
  450. Raises:
  451. AssertionError: If more than one image is attempted to be set.
  452. Examples:
  453. >>> predictor = Predictor()
  454. >>> predictor.set_image("path/to/image.jpg")
  455. >>> predictor.set_image(cv2.imread("path/to/image.jpg"))
  456. Notes:
  457. - This method should be called before performing inference on a new image.
  458. - The extracted features are stored in the `self.features` attribute for later use.
  459. """
  460. if self.model is None:
  461. self.setup_model(model=None)
  462. self.setup_source(image)
  463. assert len(self.dataset) == 1, "`set_image` only supports setting one image!"
  464. for batch in self.dataset:
  465. im = self.preprocess(batch[1])
  466. self.features = self.get_im_features(im)
  467. break
  468. def get_im_features(self, im):
  469. """Extracts image features using the SAM model's image encoder for subsequent mask prediction."""
  470. assert isinstance(self.imgsz, (tuple, list)) and self.imgsz[0] == self.imgsz[1], (
  471. f"SAM models only support square image size, but got {self.imgsz}."
  472. )
  473. self.model.set_imgsz(self.imgsz)
  474. return self.model.image_encoder(im)
  475. def set_prompts(self, prompts):
  476. """Sets prompts for subsequent inference operations."""
  477. self.prompts = prompts
  478. def reset_image(self):
  479. """Resets the current image and its features, clearing them for subsequent inference."""
  480. self.im = None
  481. self.features = None
  482. @staticmethod
  483. def remove_small_regions(masks, min_area=0, nms_thresh=0.7):
  484. """
  485. Remove small disconnected regions and holes from segmentation masks.
  486. This function performs post-processing on segmentation masks generated by the Segment Anything Model (SAM).
  487. It removes small disconnected regions and holes from the input masks, and then performs Non-Maximum
  488. Suppression (NMS) to eliminate any newly created duplicate boxes.
  489. Args:
  490. masks (torch.Tensor): Segmentation masks to be processed, with shape (N, H, W) where N is the number of
  491. masks, H is height, and W is width.
  492. min_area (int): Minimum area threshold for removing disconnected regions and holes. Regions smaller than
  493. this will be removed.
  494. nms_thresh (float): IoU threshold for the NMS algorithm to remove duplicate boxes.
  495. Returns:
  496. new_masks (torch.Tensor): Processed masks with small regions removed, shape (N, H, W).
  497. keep (List[int]): Indices of remaining masks after NMS, for filtering corresponding boxes.
  498. Examples:
  499. >>> masks = torch.rand(5, 640, 640) > 0.5 # 5 random binary masks
  500. >>> new_masks, keep = remove_small_regions(masks, min_area=100, nms_thresh=0.7)
  501. >>> print(f"Original masks: {masks.shape}, Processed masks: {new_masks.shape}")
  502. >>> print(f"Indices of kept masks: {keep}")
  503. """
  504. import torchvision # scope for faster 'import ultralytics'
  505. if len(masks) == 0:
  506. return masks
  507. # Filter small disconnected regions and holes
  508. new_masks = []
  509. scores = []
  510. for mask in masks:
  511. mask = mask.cpu().numpy().astype(np.uint8)
  512. mask, changed = remove_small_regions(mask, min_area, mode="holes")
  513. unchanged = not changed
  514. mask, changed = remove_small_regions(mask, min_area, mode="islands")
  515. unchanged = unchanged and not changed
  516. new_masks.append(torch.as_tensor(mask).unsqueeze(0))
  517. # Give score=0 to changed masks and 1 to unchanged masks so NMS prefers masks not needing postprocessing
  518. scores.append(float(unchanged))
  519. # Recalculate boxes and remove any new duplicates
  520. new_masks = torch.cat(new_masks, dim=0)
  521. boxes = batched_mask_to_box(new_masks)
  522. keep = torchvision.ops.nms(boxes.float(), torch.as_tensor(scores), nms_thresh)
  523. return new_masks[keep].to(device=masks.device, dtype=masks.dtype), keep
  524. class SAM2Predictor(Predictor):
  525. """
  526. SAM2Predictor class for advanced image segmentation using Segment Anything Model 2 architecture.
  527. This class extends the base Predictor class to implement SAM2-specific functionality for image
  528. segmentation tasks. It provides methods for model initialization, feature extraction, and
  529. prompt-based inference.
  530. Attributes:
  531. _bb_feat_sizes (List[Tuple[int, int]]): Feature sizes for different backbone levels.
  532. model (torch.nn.Module): The loaded SAM2 model.
  533. device (torch.device): The device (CPU or GPU) on which the model is loaded.
  534. features (Dict[str, torch.Tensor]): Cached image features for efficient inference.
  535. segment_all (bool): Flag to indicate if all segments should be predicted.
  536. prompts (Dict): Dictionary to store various types of prompts for inference.
  537. Methods:
  538. get_model: Retrieves and initializes the SAM2 model.
  539. prompt_inference: Performs image segmentation inference based on various prompts.
  540. set_image: Preprocesses and sets a single image for inference.
  541. get_im_features: Extracts and processes image features using SAM2's image encoder.
  542. Examples:
  543. >>> predictor = SAM2Predictor(cfg)
  544. >>> predictor.set_image("path/to/image.jpg")
  545. >>> bboxes = [[100, 100, 200, 200]]
  546. >>> result = predictor(bboxes=bboxes)[0]
  547. >>> print(f"Predicted {len(result.masks)} masks with average score {result.boxes.conf.mean():.2f}")
  548. """
  549. _bb_feat_sizes = [
  550. (256, 256),
  551. (128, 128),
  552. (64, 64),
  553. ]
  554. def get_model(self):
  555. """Retrieves and initializes the Segment Anything Model 2 (SAM2) for image segmentation tasks."""
  556. return build_sam(self.args.model)
  557. def prompt_inference(
  558. self,
  559. im,
  560. bboxes=None,
  561. points=None,
  562. labels=None,
  563. masks=None,
  564. multimask_output=False,
  565. img_idx=-1,
  566. ):
  567. """
  568. Performs image segmentation inference based on various prompts using SAM2 architecture.
  569. This method leverages the Segment Anything Model 2 (SAM2) to generate segmentation masks for input images
  570. based on provided prompts such as bounding boxes, points, or existing masks. It supports both single and
  571. multi-object prediction scenarios.
  572. Args:
  573. im (torch.Tensor): Preprocessed input image tensor with shape (N, C, H, W).
  574. bboxes (np.ndarray | List[List[float]] | None): Bounding boxes in XYXY format with shape (N, 4).
  575. points (np.ndarray | List[List[float]] | None): Object location points with shape (N, 2), in pixels.
  576. labels (np.ndarray | List[int] | None): Point prompt labels with shape (N,). 1 = foreground, 0 = background.
  577. masks (np.ndarray | None): Low-resolution masks from previous predictions with shape (N, H, W).
  578. multimask_output (bool): Flag to return multiple masks for ambiguous prompts.
  579. img_idx (int): Index of the image in the batch to process.
  580. Returns:
  581. (np.ndarray): Output masks with shape (C, H, W), where C is the number of generated masks.
  582. (np.ndarray): Quality scores for each mask, with length C.
  583. Examples:
  584. >>> predictor = SAM2Predictor(cfg)
  585. >>> image = torch.rand(1, 3, 640, 640)
  586. >>> bboxes = [[100, 100, 200, 200]]
  587. >>> result = predictor(image, bboxes=bboxes)[0]
  588. >>> print(f"Generated {result.masks.shape[0]} masks with average score {result.boxes.conf.mean():.2f}")
  589. Notes:
  590. - The method supports batched inference for multiple objects when points or bboxes are provided.
  591. - Input prompts (bboxes, points) are automatically scaled to match the input image dimensions.
  592. - When both bboxes and points are provided, they are merged into a single 'points' input for the model.
  593. References:
  594. - SAM2 Paper: [Add link to SAM2 paper when available]
  595. """
  596. features = self.get_im_features(im) if self.features is None else self.features
  597. points, labels, masks = self._prepare_prompts(im.shape[2:], bboxes, points, labels, masks)
  598. points = (points, labels) if points is not None else None
  599. sparse_embeddings, dense_embeddings = self.model.sam_prompt_encoder(
  600. points=points,
  601. boxes=None,
  602. masks=masks,
  603. )
  604. # Predict masks
  605. batched_mode = points is not None and points[0].shape[0] > 1 # multi object prediction
  606. high_res_features = [feat_level[img_idx].unsqueeze(0) for feat_level in features["high_res_feats"]]
  607. pred_masks, pred_scores, _, _ = self.model.sam_mask_decoder(
  608. image_embeddings=features["image_embed"][img_idx].unsqueeze(0),
  609. image_pe=self.model.sam_prompt_encoder.get_dense_pe(),
  610. sparse_prompt_embeddings=sparse_embeddings,
  611. dense_prompt_embeddings=dense_embeddings,
  612. multimask_output=multimask_output,
  613. repeat_image=batched_mode,
  614. high_res_features=high_res_features,
  615. )
  616. # (N, d, H, W) --> (N*d, H, W), (N, d) --> (N*d, )
  617. # `d` could be 1 or 3 depends on `multimask_output`.
  618. return pred_masks.flatten(0, 1), pred_scores.flatten(0, 1)
  619. def _prepare_prompts(self, dst_shape, bboxes=None, points=None, labels=None, masks=None):
  620. """
  621. Prepares and transforms the input prompts for processing based on the destination shape.
  622. Args:
  623. dst_shape (tuple): The target shape (height, width) for the prompts.
  624. bboxes (np.ndarray | List | None): Bounding boxes in XYXY format with shape (N, 4).
  625. points (np.ndarray | List | None): Points indicating object locations with shape (N, 2) or (N, num_points, 2), in pixels.
  626. labels (np.ndarray | List | None): Point prompt labels with shape (N,) or (N, num_points). 1 for foreground, 0 for background.
  627. masks (List | np.ndarray, Optional): Masks for the objects, where each mask is a 2D array.
  628. Raises:
  629. AssertionError: If the number of points don't match the number of labels, in case labels were passed.
  630. Returns:
  631. (tuple): A tuple containing transformed points, labels, and masks.
  632. """
  633. bboxes, points, labels, masks = super()._prepare_prompts(dst_shape, bboxes, points, labels, masks)
  634. if bboxes is not None:
  635. bboxes = bboxes.view(-1, 2, 2)
  636. bbox_labels = torch.tensor([[2, 3]], dtype=torch.int32, device=bboxes.device).expand(len(bboxes), -1)
  637. # NOTE: merge "boxes" and "points" into a single "points" input
  638. # (where boxes are added at the beginning) to model.sam_prompt_encoder
  639. if points is not None:
  640. points = torch.cat([bboxes, points], dim=1)
  641. labels = torch.cat([bbox_labels, labels], dim=1)
  642. else:
  643. points, labels = bboxes, bbox_labels
  644. return points, labels, masks
  645. def set_image(self, image):
  646. """
  647. Preprocesses and sets a single image for inference using the SAM2 model.
  648. This method initializes the model if not already done, configures the data source to the specified image,
  649. and preprocesses the image for feature extraction. It supports setting only one image at a time.
  650. Args:
  651. image (str | np.ndarray): Path to the image file as a string, or a numpy array representing the image.
  652. Raises:
  653. AssertionError: If more than one image is attempted to be set.
  654. Examples:
  655. >>> predictor = SAM2Predictor()
  656. >>> predictor.set_image("path/to/image.jpg")
  657. >>> predictor.set_image(np.array([...])) # Using a numpy array
  658. Notes:
  659. - This method must be called before performing any inference on a new image.
  660. - The method caches the extracted features for efficient subsequent inferences on the same image.
  661. - Only one image can be set at a time. To process multiple images, call this method for each new image.
  662. """
  663. if self.model is None:
  664. self.setup_model(model=None)
  665. self.setup_source(image)
  666. assert len(self.dataset) == 1, "`set_image` only supports setting one image!"
  667. for batch in self.dataset:
  668. im = self.preprocess(batch[1])
  669. self.features = self.get_im_features(im)
  670. break
  671. def get_im_features(self, im):
  672. """Extracts image features from the SAM image encoder for subsequent processing."""
  673. assert isinstance(self.imgsz, (tuple, list)) and self.imgsz[0] == self.imgsz[1], (
  674. f"SAM 2 models only support square image size, but got {self.imgsz}."
  675. )
  676. self.model.set_imgsz(self.imgsz)
  677. self._bb_feat_sizes = [[x // (4 * i) for x in self.imgsz] for i in [1, 2, 4]]
  678. backbone_out = self.model.forward_image(im)
  679. _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out)
  680. if self.model.directly_add_no_mem_embed:
  681. vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
  682. feats = [
  683. feat.permute(1, 2, 0).view(1, -1, *feat_size)
  684. for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1])
  685. ][::-1]
  686. return {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
  687. class SAM2VideoPredictor(SAM2Predictor):
  688. """
  689. SAM2VideoPredictor to handle user interactions with videos and manage inference states.
  690. This class extends the functionality of SAM2Predictor to support video processing and maintains
  691. the state of inference operations. It includes configurations for managing non-overlapping masks,
  692. clearing memory for non-conditional inputs, and setting up callbacks for prediction events.
  693. Attributes:
  694. inference_state (Dict): A dictionary to store the current state of inference operations.
  695. non_overlap_masks (bool): A flag indicating whether masks should be non-overlapping.
  696. clear_non_cond_mem_around_input (bool): A flag to control clearing non-conditional memory around inputs.
  697. clear_non_cond_mem_for_multi_obj (bool): A flag to control clearing non-conditional memory for multi-object scenarios.
  698. callbacks (Dict): A dictionary of callbacks for various prediction lifecycle events.
  699. Args:
  700. cfg (Dict, Optional): Configuration settings for the predictor. Defaults to DEFAULT_CFG.
  701. overrides (Dict, Optional): Additional configuration overrides. Defaults to None.
  702. _callbacks (List, Optional): Custom callbacks to be added. Defaults to None.
  703. Note:
  704. The `fill_hole_area` attribute is defined but not used in the current implementation.
  705. """
  706. # fill_hole_area = 8 # not used
  707. def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
  708. """
  709. Initialize the predictor with configuration and optional overrides.
  710. This constructor initializes the SAM2VideoPredictor with a given configuration, applies any
  711. specified overrides, and sets up the inference state along with certain flags
  712. that control the behavior of the predictor.
  713. Args:
  714. cfg (Dict): Configuration dictionary containing default settings.
  715. overrides (Dict | None): Dictionary of values to override default configuration.
  716. _callbacks (Dict | None): Dictionary of callback functions to customize behavior.
  717. Examples:
  718. >>> predictor = SAM2VideoPredictor(cfg=DEFAULT_CFG)
  719. >>> predictor_example_with_imgsz = SAM2VideoPredictor(overrides={"imgsz": 640})
  720. >>> predictor_example_with_callback = SAM2VideoPredictor(_callbacks={"on_predict_start": custom_callback})
  721. """
  722. super().__init__(cfg, overrides, _callbacks)
  723. self.inference_state = {}
  724. self.non_overlap_masks = True
  725. self.clear_non_cond_mem_around_input = False
  726. self.clear_non_cond_mem_for_multi_obj = False
  727. self.callbacks["on_predict_start"].append(self.init_state)
  728. def get_model(self):
  729. """
  730. Retrieves and configures the model with binarization enabled.
  731. Note:
  732. This method overrides the base class implementation to set the binarize flag to True.
  733. """
  734. model = super().get_model()
  735. model.set_binarize(True)
  736. return model
  737. def inference(self, im, bboxes=None, points=None, labels=None, masks=None):
  738. """
  739. Perform image segmentation inference based on the given input cues, using the currently loaded image. This
  740. method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt encoder, and
  741. mask decoder for real-time and promptable segmentation tasks.
  742. Args:
  743. im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
  744. bboxes (np.ndarray | List, optional): Bounding boxes with shape (N, 4), in XYXY format.
  745. points (np.ndarray | List, optional): Points indicating object locations with shape (N, 2), in pixels.
  746. labels (np.ndarray | List, optional): Labels for point prompts, shape (N, ). 1 = foreground, 0 = background.
  747. masks (np.ndarray, optional): Low-resolution masks from previous predictions shape (N,H,W). For SAM H=W=256.
  748. Returns:
  749. (np.ndarray): The output masks in shape CxHxW, where C is the number of generated masks.
  750. (np.ndarray): An array of length C containing quality scores predicted by the model for each mask.
  751. """
  752. # Override prompts if any stored in self.prompts
  753. bboxes = self.prompts.pop("bboxes", bboxes)
  754. points = self.prompts.pop("points", points)
  755. masks = self.prompts.pop("masks", masks)
  756. frame = self.dataset.frame
  757. self.inference_state["im"] = im
  758. output_dict = self.inference_state["output_dict"]
  759. if len(output_dict["cond_frame_outputs"]) == 0: # initialize prompts
  760. points, labels, masks = self._prepare_prompts(im.shape[2:], bboxes, points, labels, masks)
  761. if points is not None:
  762. for i in range(len(points)):
  763. self.add_new_prompts(obj_id=i, points=points[[i]], labels=labels[[i]], frame_idx=frame)
  764. elif masks is not None:
  765. for i in range(len(masks)):
  766. self.add_new_prompts(obj_id=i, masks=masks[[i]], frame_idx=frame)
  767. self.propagate_in_video_preflight()
  768. consolidated_frame_inds = self.inference_state["consolidated_frame_inds"]
  769. batch_size = len(self.inference_state["obj_idx_to_id"])
  770. if len(output_dict["cond_frame_outputs"]) == 0:
  771. raise RuntimeError("No points are provided; please add points first")
  772. if frame in consolidated_frame_inds["cond_frame_outputs"]:
  773. storage_key = "cond_frame_outputs"
  774. current_out = output_dict[storage_key][frame]
  775. if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1):
  776. # clear non-conditioning memory of the surrounding frames
  777. self._clear_non_cond_mem_around_input(frame)
  778. elif frame in consolidated_frame_inds["non_cond_frame_outputs"]:
  779. storage_key = "non_cond_frame_outputs"
  780. current_out = output_dict[storage_key][frame]
  781. else:
  782. storage_key = "non_cond_frame_outputs"
  783. current_out = self._run_single_frame_inference(
  784. output_dict=output_dict,
  785. frame_idx=frame,
  786. batch_size=batch_size,
  787. is_init_cond_frame=False,
  788. point_inputs=None,
  789. mask_inputs=None,
  790. reverse=False,
  791. run_mem_encoder=True,
  792. )
  793. output_dict[storage_key][frame] = current_out
  794. # Create slices of per-object outputs for subsequent interaction with each
  795. # individual object after tracking.
  796. self._add_output_per_object(frame, current_out, storage_key)
  797. self.inference_state["frames_already_tracked"].append(frame)
  798. pred_masks = current_out["pred_masks"].flatten(0, 1)
  799. pred_masks = pred_masks[(pred_masks > self.model.mask_threshold).sum((1, 2)) > 0] # filter blank masks
  800. return pred_masks, torch.ones(len(pred_masks), dtype=pred_masks.dtype, device=pred_masks.device)
  801. def postprocess(self, preds, img, orig_imgs):
  802. """
  803. Post-processes the predictions to apply non-overlapping constraints if required.
  804. This method extends the post-processing functionality by applying non-overlapping constraints
  805. to the predicted masks if the `non_overlap_masks` flag is set to True. This ensures that
  806. the masks do not overlap, which can be useful for certain applications.
  807. Args:
  808. preds (Tuple[torch.Tensor]): The predictions from the model.
  809. img (torch.Tensor): The processed image tensor.
  810. orig_imgs (List[np.ndarray]): The original images before processing.
  811. Returns:
  812. results (list): The post-processed predictions.
  813. Note:
  814. If `non_overlap_masks` is True, the method applies constraints to ensure non-overlapping masks.
  815. """
  816. results = super().postprocess(preds, img, orig_imgs)
  817. if self.non_overlap_masks:
  818. for result in results:
  819. if result.masks is None or len(result.masks) == 0:
  820. continue
  821. result.masks.data = self.model._apply_non_overlapping_constraints(result.masks.data.unsqueeze(0))[0]
  822. return results
  823. @smart_inference_mode()
  824. def add_new_prompts(
  825. self,
  826. obj_id,
  827. points=None,
  828. labels=None,
  829. masks=None,
  830. frame_idx=0,
  831. ):
  832. """
  833. Adds new points or masks to a specific frame for a given object ID.
  834. This method updates the inference state with new prompts (points or masks) for a specified
  835. object and frame index. It ensures that the prompts are either points or masks, but not both,
  836. and updates the internal state accordingly. It also handles the generation of new segmentations
  837. based on the provided prompts and the existing state.
  838. Args:
  839. obj_id (int): The ID of the object to which the prompts are associated.
  840. points (torch.Tensor, Optional): The coordinates of the points of interest. Defaults to None.
  841. labels (torch.Tensor, Optional): The labels corresponding to the points. Defaults to None.
  842. masks (torch.Tensor, optional): Binary masks for the object. Defaults to None.
  843. frame_idx (int, optional): The index of the frame to which the prompts are applied. Defaults to 0.
  844. Returns:
  845. (tuple): A tuple containing the flattened predicted masks and a tensor of ones indicating the number of objects.
  846. Raises:
  847. AssertionError: If both `masks` and `points` are provided, or neither is provided.
  848. Note:
  849. - Only one type of prompt (either points or masks) can be added per call.
  850. - If the frame is being tracked for the first time, it is treated as an initial conditioning frame.
  851. - The method handles the consolidation of outputs and resizing of masks to the original video resolution.
  852. """
  853. assert (masks is None) ^ (points is None), "'masks' and 'points' prompts are not compatible with each other."
  854. obj_idx = self._obj_id_to_idx(obj_id)
  855. point_inputs = None
  856. pop_key = "point_inputs_per_obj"
  857. if points is not None:
  858. point_inputs = {"point_coords": points, "point_labels": labels}
  859. self.inference_state["point_inputs_per_obj"][obj_idx][frame_idx] = point_inputs
  860. pop_key = "mask_inputs_per_obj"
  861. self.inference_state["mask_inputs_per_obj"][obj_idx][frame_idx] = masks
  862. self.inference_state[pop_key][obj_idx].pop(frame_idx, None)
  863. # If this frame hasn't been tracked before, we treat it as an initial conditioning
  864. # frame, meaning that the inputs points are to generate segments on this frame without
  865. # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
  866. # the input points will be used to correct the already tracked masks.
  867. is_init_cond_frame = frame_idx not in self.inference_state["frames_already_tracked"]
  868. obj_output_dict = self.inference_state["output_dict_per_obj"][obj_idx]
  869. obj_temp_output_dict = self.inference_state["temp_output_dict_per_obj"][obj_idx]
  870. # Add a frame to conditioning output if it's an initial conditioning frame or
  871. # if the model sees all frames receiving clicks/mask as conditioning frames.
  872. is_cond = is_init_cond_frame or self.model.add_all_frames_to_correct_as_cond
  873. storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
  874. # Get any previously predicted mask logits on this object and feed it along with
  875. # the new clicks into the SAM mask decoder.
  876. prev_sam_mask_logits = None
  877. # lookup temporary output dict first, which contains the most recent output
  878. # (if not found, then lookup conditioning and non-conditioning frame output)
  879. if point_inputs is not None:
  880. prev_out = (
  881. obj_temp_output_dict[storage_key].get(frame_idx)
  882. or obj_output_dict["cond_frame_outputs"].get(frame_idx)
  883. or obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
  884. )
  885. if prev_out is not None and prev_out.get("pred_masks") is not None:
  886. prev_sam_mask_logits = prev_out["pred_masks"].to(device=self.device, non_blocking=True)
  887. # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues.
  888. prev_sam_mask_logits.clamp_(-32.0, 32.0)
  889. current_out = self._run_single_frame_inference(
  890. output_dict=obj_output_dict, # run on the slice of a single object
  891. frame_idx=frame_idx,
  892. batch_size=1, # run on the slice of a single object
  893. is_init_cond_frame=is_init_cond_frame,
  894. point_inputs=point_inputs,
  895. mask_inputs=masks,
  896. reverse=False,
  897. # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
  898. # at the beginning of `propagate_in_video` (after user finalize their clicks). This
  899. # allows us to enforce non-overlapping constraints on all objects before encoding
  900. # them into memory.
  901. run_mem_encoder=False,
  902. prev_sam_mask_logits=prev_sam_mask_logits,
  903. )
  904. # Add the output to the output dict (to be used as future memory)
  905. obj_temp_output_dict[storage_key][frame_idx] = current_out
  906. # Resize the output mask to the original video resolution
  907. consolidated_out = self._consolidate_temp_output_across_obj(
  908. frame_idx,
  909. is_cond=is_cond,
  910. run_mem_encoder=False,
  911. )
  912. pred_masks = consolidated_out["pred_masks"].flatten(0, 1)
  913. return pred_masks.flatten(0, 1), torch.ones(1, dtype=pred_masks.dtype, device=pred_masks.device)
  914. @smart_inference_mode()
  915. def propagate_in_video_preflight(self):
  916. """
  917. Prepare inference_state and consolidate temporary outputs before tracking.
  918. This method marks the start of tracking, disallowing the addition of new objects until the session is reset.
  919. It consolidates temporary outputs from `temp_output_dict_per_obj` and merges them into `output_dict`.
  920. Additionally, it clears non-conditioning memory around input frames and ensures that the state is consistent
  921. with the provided inputs.
  922. """
  923. # Tracking has started and we don't allow adding new objects until session is reset.
  924. self.inference_state["tracking_has_started"] = True
  925. batch_size = len(self.inference_state["obj_idx_to_id"])
  926. # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and
  927. # add them into "output_dict".
  928. temp_output_dict_per_obj = self.inference_state["temp_output_dict_per_obj"]
  929. output_dict = self.inference_state["output_dict"]
  930. # "consolidated_frame_inds" contains indices of those frames where consolidated
  931. # temporary outputs have been added (either in this call or any previous calls
  932. # to `propagate_in_video_preflight`).
  933. consolidated_frame_inds = self.inference_state["consolidated_frame_inds"]
  934. for is_cond in {False, True}:
  935. # Separately consolidate conditioning and non-conditioning temp outputs
  936. storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
  937. # Find all the frames that contain temporary outputs for any objects
  938. # (these should be the frames that have just received clicks for mask inputs
  939. # via `add_new_points` or `add_new_mask`)
  940. temp_frame_inds = set()
  941. for obj_temp_output_dict in temp_output_dict_per_obj.values():
  942. temp_frame_inds.update(obj_temp_output_dict[storage_key].keys())
  943. consolidated_frame_inds[storage_key].update(temp_frame_inds)
  944. # consolidate the temporary output across all objects on this frame
  945. for frame_idx in temp_frame_inds:
  946. consolidated_out = self._consolidate_temp_output_across_obj(
  947. frame_idx, is_cond=is_cond, run_mem_encoder=True
  948. )
  949. # merge them into "output_dict" and also create per-object slices
  950. output_dict[storage_key][frame_idx] = consolidated_out
  951. self._add_output_per_object(frame_idx, consolidated_out, storage_key)
  952. if self.clear_non_cond_mem_around_input and (self.clear_non_cond_mem_for_multi_obj or batch_size <= 1):
  953. # clear non-conditioning memory of the surrounding frames
  954. self._clear_non_cond_mem_around_input(frame_idx)
  955. # clear temporary outputs in `temp_output_dict_per_obj`
  956. for obj_temp_output_dict in temp_output_dict_per_obj.values():
  957. obj_temp_output_dict[storage_key].clear()
  958. # edge case: if an output is added to "cond_frame_outputs", we remove any prior
  959. # output on the same frame in "non_cond_frame_outputs"
  960. for frame_idx in output_dict["cond_frame_outputs"]:
  961. output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
  962. for obj_output_dict in self.inference_state["output_dict_per_obj"].values():
  963. for frame_idx in obj_output_dict["cond_frame_outputs"]:
  964. obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
  965. for frame_idx in consolidated_frame_inds["cond_frame_outputs"]:
  966. assert frame_idx in output_dict["cond_frame_outputs"]
  967. consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx)
  968. # Make sure that the frame indices in "consolidated_frame_inds" are exactly those frames
  969. # with either points or mask inputs (which should be true under a correct workflow).
  970. all_consolidated_frame_inds = (
  971. consolidated_frame_inds["cond_frame_outputs"] | consolidated_frame_inds["non_cond_frame_outputs"]
  972. )
  973. input_frames_inds = set()
  974. for point_inputs_per_frame in self.inference_state["point_inputs_per_obj"].values():
  975. input_frames_inds.update(point_inputs_per_frame.keys())
  976. for mask_inputs_per_frame in self.inference_state["mask_inputs_per_obj"].values():
  977. input_frames_inds.update(mask_inputs_per_frame.keys())
  978. assert all_consolidated_frame_inds == input_frames_inds
  979. @staticmethod
  980. def init_state(predictor):
  981. """
  982. Initialize an inference state for the predictor.
  983. This function sets up the initial state required for performing inference on video data.
  984. It includes initializing various dictionaries and ordered dictionaries that will store
  985. inputs, outputs, and other metadata relevant to the tracking process.
  986. Args:
  987. predictor (SAM2VideoPredictor): The predictor object for which to initialize the state.
  988. """
  989. if len(predictor.inference_state) > 0: # means initialized
  990. return
  991. assert predictor.dataset is not None
  992. assert predictor.dataset.mode == "video"
  993. inference_state = {
  994. "num_frames": predictor.dataset.frames,
  995. "point_inputs_per_obj": {}, # inputs points on each frame
  996. "mask_inputs_per_obj": {}, # inputs mask on each frame
  997. "constants": {}, # values that don't change across frames (so we only need to hold one copy of them)
  998. # mapping between client-side object id and model-side object index
  999. "obj_id_to_idx": OrderedDict(),
  1000. "obj_idx_to_id": OrderedDict(),
  1001. "obj_ids": [],
  1002. # A storage to hold the model's tracking results and states on each frame
  1003. "output_dict": {
  1004. "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  1005. "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  1006. },
  1007. # Slice (view) of each object tracking results, sharing the same memory with "output_dict"
  1008. "output_dict_per_obj": {},
  1009. # A temporary storage to hold new outputs when user interact with a frame
  1010. # to add clicks or mask (it's merged into "output_dict" before propagation starts)
  1011. "temp_output_dict_per_obj": {},
  1012. # Frames that already holds consolidated outputs from click or mask inputs
  1013. # (we directly use their consolidated outputs during tracking)
  1014. "consolidated_frame_inds": {
  1015. "cond_frame_outputs": set(), # set containing frame indices
  1016. "non_cond_frame_outputs": set(), # set containing frame indices
  1017. },
  1018. # metadata for each tracking frame (e.g. which direction it's tracked)
  1019. "tracking_has_started": False,
  1020. "frames_already_tracked": [],
  1021. }
  1022. predictor.inference_state = inference_state
  1023. def get_im_features(self, im, batch=1):
  1024. """
  1025. Extracts and processes image features using SAM2's image encoder for subsequent segmentation tasks.
  1026. Args:
  1027. im (torch.Tensor): The input image tensor.
  1028. batch (int, optional): The batch size for expanding features if there are multiple prompts. Defaults to 1.
  1029. Returns:
  1030. vis_feats (torch.Tensor): The visual features extracted from the image.
  1031. vis_pos_embed (torch.Tensor): The positional embeddings for the visual features.
  1032. feat_sizes (List(Tuple[int])): A list containing the sizes of the extracted features.
  1033. Note:
  1034. - If `batch` is greater than 1, the features are expanded to fit the batch size.
  1035. - The method leverages the model's `_prepare_backbone_features` method to prepare the backbone features.
  1036. """
  1037. backbone_out = self.model.forward_image(im)
  1038. if batch > 1: # expand features if there's more than one prompt
  1039. for i, feat in enumerate(backbone_out["backbone_fpn"]):
  1040. backbone_out["backbone_fpn"][i] = feat.expand(batch, -1, -1, -1)
  1041. for i, pos in enumerate(backbone_out["vision_pos_enc"]):
  1042. pos = pos.expand(batch, -1, -1, -1)
  1043. backbone_out["vision_pos_enc"][i] = pos
  1044. _, vis_feats, vis_pos_embed, feat_sizes = self.model._prepare_backbone_features(backbone_out)
  1045. return vis_feats, vis_pos_embed, feat_sizes
  1046. def _obj_id_to_idx(self, obj_id):
  1047. """
  1048. Map client-side object id to model-side object index.
  1049. Args:
  1050. obj_id (int): The unique identifier of the object provided by the client side.
  1051. Returns:
  1052. obj_idx (int): The index of the object on the model side.
  1053. Raises:
  1054. RuntimeError: If an attempt is made to add a new object after tracking has started.
  1055. Note:
  1056. - The method updates or retrieves mappings between object IDs and indices stored in
  1057. `inference_state`.
  1058. - It ensures that new objects can only be added before tracking commences.
  1059. - It maintains two-way mappings between IDs and indices (`obj_id_to_idx` and `obj_idx_to_id`).
  1060. - Additional data structures are initialized for the new object to store inputs and outputs.
  1061. """
  1062. obj_idx = self.inference_state["obj_id_to_idx"].get(obj_id, None)
  1063. if obj_idx is not None:
  1064. return obj_idx
  1065. # This is a new object id not sent to the server before. We only allow adding
  1066. # new objects *before* the tracking starts.
  1067. allow_new_object = not self.inference_state["tracking_has_started"]
  1068. if allow_new_object:
  1069. # get the next object slot
  1070. obj_idx = len(self.inference_state["obj_id_to_idx"])
  1071. self.inference_state["obj_id_to_idx"][obj_id] = obj_idx
  1072. self.inference_state["obj_idx_to_id"][obj_idx] = obj_id
  1073. self.inference_state["obj_ids"] = list(self.inference_state["obj_id_to_idx"])
  1074. # set up input and output structures for this object
  1075. self.inference_state["point_inputs_per_obj"][obj_idx] = {}
  1076. self.inference_state["mask_inputs_per_obj"][obj_idx] = {}
  1077. self.inference_state["output_dict_per_obj"][obj_idx] = {
  1078. "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  1079. "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  1080. }
  1081. self.inference_state["temp_output_dict_per_obj"][obj_idx] = {
  1082. "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  1083. "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
  1084. }
  1085. return obj_idx
  1086. else:
  1087. raise RuntimeError(
  1088. f"Cannot add new object id {obj_id} after tracking starts. "
  1089. f"All existing object ids: {self.inference_state['obj_ids']}. "
  1090. f"Please call 'reset_state' to restart from scratch."
  1091. )
  1092. def _run_single_frame_inference(
  1093. self,
  1094. output_dict,
  1095. frame_idx,
  1096. batch_size,
  1097. is_init_cond_frame,
  1098. point_inputs,
  1099. mask_inputs,
  1100. reverse,
  1101. run_mem_encoder,
  1102. prev_sam_mask_logits=None,
  1103. ):
  1104. """
  1105. Run tracking on a single frame based on current inputs and previous memory.
  1106. Args:
  1107. output_dict (Dict): The dictionary containing the output states of the tracking process.
  1108. frame_idx (int): The index of the current frame.
  1109. batch_size (int): The batch size for processing the frame.
  1110. is_init_cond_frame (bool): Indicates if the current frame is an initial conditioning frame.
  1111. point_inputs (Dict, Optional): Input points and their labels. Defaults to None.
  1112. mask_inputs (torch.Tensor, Optional): Input binary masks. Defaults to None.
  1113. reverse (bool): Indicates if the tracking should be performed in reverse order.
  1114. run_mem_encoder (bool): Indicates if the memory encoder should be executed.
  1115. prev_sam_mask_logits (torch.Tensor, Optional): Previous mask logits for the current object. Defaults to None.
  1116. Returns:
  1117. current_out (dict): A dictionary containing the output of the tracking step, including updated features and predictions.
  1118. Raises:
  1119. AssertionError: If both `point_inputs` and `mask_inputs` are provided, or neither is provided.
  1120. Note:
  1121. - The method assumes that `point_inputs` and `mask_inputs` are mutually exclusive.
  1122. - The method retrieves image features using the `get_im_features` method.
  1123. - The `maskmem_pos_enc` is assumed to be constant across frames, hence only one copy is stored.
  1124. - The `fill_holes_in_mask_scores` function is commented out and currently unsupported due to CUDA extension requirements.
  1125. """
  1126. # Retrieve correct image features
  1127. current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(
  1128. self.inference_state["im"], batch_size
  1129. )
  1130. # point and mask should not appear as input simultaneously on the same frame
  1131. assert point_inputs is None or mask_inputs is None
  1132. current_out = self.model.track_step(
  1133. frame_idx=frame_idx,
  1134. is_init_cond_frame=is_init_cond_frame,
  1135. current_vision_feats=current_vision_feats,
  1136. current_vision_pos_embeds=current_vision_pos_embeds,
  1137. feat_sizes=feat_sizes,
  1138. point_inputs=point_inputs,
  1139. mask_inputs=mask_inputs,
  1140. output_dict=output_dict,
  1141. num_frames=self.inference_state["num_frames"],
  1142. track_in_reverse=reverse,
  1143. run_mem_encoder=run_mem_encoder,
  1144. prev_sam_mask_logits=prev_sam_mask_logits,
  1145. )
  1146. maskmem_features = current_out["maskmem_features"]
  1147. if maskmem_features is not None:
  1148. current_out["maskmem_features"] = maskmem_features.to(
  1149. dtype=torch.float16, device=self.device, non_blocking=True
  1150. )
  1151. # NOTE: Do not support the `fill_holes_in_mask_scores` function since it needs cuda extensions
  1152. # potentially fill holes in the predicted masks
  1153. # if self.fill_hole_area > 0:
  1154. # pred_masks = current_out["pred_masks"].to(self.device, non_blocking=True)
  1155. # pred_masks = fill_holes_in_mask_scores(pred_masks, self.fill_hole_area)
  1156. # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
  1157. current_out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(current_out["maskmem_pos_enc"])
  1158. return current_out
  1159. def _get_maskmem_pos_enc(self, out_maskmem_pos_enc):
  1160. """
  1161. Caches and manages the positional encoding for mask memory across frames and objects.
  1162. This method optimizes storage by caching the positional encoding (`maskmem_pos_enc`) for
  1163. mask memory, which is constant across frames and objects, thus reducing the amount of
  1164. redundant information stored during an inference session. It checks if the positional
  1165. encoding has already been cached; if not, it caches a slice of the provided encoding.
  1166. If the batch size is greater than one, it expands the cached positional encoding to match
  1167. the current batch size.
  1168. Args:
  1169. out_maskmem_pos_enc (List[torch.Tensor] or None): The positional encoding for mask memory.
  1170. Should be a list of tensors or None.
  1171. Returns:
  1172. out_maskmem_pos_enc (List[torch.Tensor]): The positional encoding for mask memory, either cached or expanded.
  1173. Note:
  1174. - The method assumes that `out_maskmem_pos_enc` is a list of tensors or None.
  1175. - Only a single object's slice is cached since the encoding is the same across objects.
  1176. - The method checks if the positional encoding has already been cached in the session's constants.
  1177. - If the batch size is greater than one, the cached encoding is expanded to fit the batch size.
  1178. """
  1179. model_constants = self.inference_state["constants"]
  1180. # "out_maskmem_pos_enc" should be either a list of tensors or None
  1181. if out_maskmem_pos_enc is not None:
  1182. if "maskmem_pos_enc" not in model_constants:
  1183. assert isinstance(out_maskmem_pos_enc, list)
  1184. # only take the slice for one object, since it's same across objects
  1185. maskmem_pos_enc = [x[:1].clone() for x in out_maskmem_pos_enc]
  1186. model_constants["maskmem_pos_enc"] = maskmem_pos_enc
  1187. else:
  1188. maskmem_pos_enc = model_constants["maskmem_pos_enc"]
  1189. # expand the cached maskmem_pos_enc to the actual batch size
  1190. batch_size = out_maskmem_pos_enc[0].size(0)
  1191. if batch_size > 1:
  1192. out_maskmem_pos_enc = [x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc]
  1193. return out_maskmem_pos_enc
  1194. def _consolidate_temp_output_across_obj(
  1195. self,
  1196. frame_idx,
  1197. is_cond=False,
  1198. run_mem_encoder=False,
  1199. ):
  1200. """
  1201. Consolidates per-object temporary outputs into a single output for all objects.
  1202. This method combines the temporary outputs for each object on a given frame into a unified
  1203. output. It fills in any missing objects either from the main output dictionary or leaves
  1204. placeholders if they do not exist in the main output. Optionally, it can re-run the memory
  1205. encoder after applying non-overlapping constraints to the object scores.
  1206. Args:
  1207. frame_idx (int): The index of the frame for which to consolidate outputs.
  1208. is_cond (bool, Optional): Indicates if the frame is considered a conditioning frame.
  1209. Defaults to False.
  1210. run_mem_encoder (bool, Optional): Specifies whether to run the memory encoder after
  1211. consolidating the outputs. Defaults to False.
  1212. Returns:
  1213. consolidated_out (dict): A consolidated output dictionary containing the combined results for all objects.
  1214. Note:
  1215. - The method initializes the consolidated output with placeholder values for missing objects.
  1216. - It searches for outputs in both the temporary and main output dictionaries.
  1217. - If `run_mem_encoder` is True, it applies non-overlapping constraints and re-runs the memory encoder.
  1218. - The `maskmem_features` and `maskmem_pos_enc` are only populated when `run_mem_encoder` is True.
  1219. """
  1220. batch_size = len(self.inference_state["obj_idx_to_id"])
  1221. storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
  1222. # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc"
  1223. # will be added when rerunning the memory encoder after applying non-overlapping
  1224. # constraints to object scores. Its "pred_masks" are prefilled with a large
  1225. # negative value (NO_OBJ_SCORE) to represent missing objects.
  1226. consolidated_out = {
  1227. "maskmem_features": None,
  1228. "maskmem_pos_enc": None,
  1229. "pred_masks": torch.full(
  1230. size=(batch_size, 1, self.imgsz[0] // 4, self.imgsz[1] // 4),
  1231. fill_value=-1024.0,
  1232. dtype=torch.float32,
  1233. device=self.device,
  1234. ),
  1235. "obj_ptr": torch.full(
  1236. size=(batch_size, self.model.hidden_dim),
  1237. fill_value=-1024.0,
  1238. dtype=torch.float32,
  1239. device=self.device,
  1240. ),
  1241. "object_score_logits": torch.full(
  1242. size=(batch_size, 1),
  1243. # default to 10.0 for object_score_logits, i.e. assuming the object is
  1244. # present as sigmoid(10)=1, same as in `predict_masks` of `MaskDecoder`
  1245. fill_value=10.0,
  1246. dtype=torch.float32,
  1247. device=self.device,
  1248. ),
  1249. }
  1250. for obj_idx in range(batch_size):
  1251. obj_temp_output_dict = self.inference_state["temp_output_dict_per_obj"][obj_idx]
  1252. obj_output_dict = self.inference_state["output_dict_per_obj"][obj_idx]
  1253. out = (
  1254. obj_temp_output_dict[storage_key].get(frame_idx)
  1255. # If the object doesn't appear in "temp_output_dict_per_obj" on this frame,
  1256. # we fall back and look up its previous output in "output_dict_per_obj".
  1257. # We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in
  1258. # "output_dict_per_obj" to find a previous output for this object.
  1259. or obj_output_dict["cond_frame_outputs"].get(frame_idx)
  1260. or obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
  1261. )
  1262. # If the object doesn't appear in "output_dict_per_obj" either, we skip it
  1263. # and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE
  1264. # placeholder above) and set its object pointer to be a dummy pointer.
  1265. if out is None:
  1266. # Fill in dummy object pointers for those objects without any inputs or
  1267. # tracking outcomes on this frame (only do it under `run_mem_encoder=True`,
  1268. # i.e. when we need to build the memory for tracking).
  1269. if run_mem_encoder:
  1270. # fill object pointer with a dummy pointer (based on an empty mask)
  1271. consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = self._get_empty_mask_ptr(frame_idx)
  1272. continue
  1273. # Add the temporary object output mask to consolidated output mask
  1274. consolidated_out["pred_masks"][obj_idx : obj_idx + 1] = out["pred_masks"]
  1275. consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"]
  1276. # Optionally, apply non-overlapping constraints on the consolidated scores and rerun the memory encoder
  1277. if run_mem_encoder:
  1278. high_res_masks = F.interpolate(
  1279. consolidated_out["pred_masks"],
  1280. size=self.imgsz,
  1281. mode="bilinear",
  1282. align_corners=False,
  1283. )
  1284. if self.model.non_overlap_masks_for_mem_enc:
  1285. high_res_masks = self.model._apply_non_overlapping_constraints(high_res_masks)
  1286. consolidated_out["maskmem_features"], consolidated_out["maskmem_pos_enc"] = self._run_memory_encoder(
  1287. batch_size=batch_size,
  1288. high_res_masks=high_res_masks,
  1289. is_mask_from_pts=True, # these frames are what the user interacted with
  1290. object_score_logits=consolidated_out["object_score_logits"],
  1291. )
  1292. return consolidated_out
  1293. def _get_empty_mask_ptr(self, frame_idx):
  1294. """
  1295. Get a dummy object pointer based on an empty mask on the current frame.
  1296. Args:
  1297. frame_idx (int): The index of the current frame for which to generate the dummy object pointer.
  1298. Returns:
  1299. (torch.Tensor): A tensor representing the dummy object pointer generated from the empty mask.
  1300. """
  1301. # Retrieve correct image features
  1302. current_vision_feats, current_vision_pos_embeds, feat_sizes = self.get_im_features(self.inference_state["im"])
  1303. # Feed the empty mask and image feature above to get a dummy object pointer
  1304. current_out = self.model.track_step(
  1305. frame_idx=frame_idx,
  1306. is_init_cond_frame=True,
  1307. current_vision_feats=current_vision_feats,
  1308. current_vision_pos_embeds=current_vision_pos_embeds,
  1309. feat_sizes=feat_sizes,
  1310. point_inputs=None,
  1311. # A dummy (empty) mask with a single object
  1312. mask_inputs=torch.zeros((1, 1, *self.imgsz), dtype=torch.float32, device=self.device),
  1313. output_dict={},
  1314. num_frames=self.inference_state["num_frames"],
  1315. track_in_reverse=False,
  1316. run_mem_encoder=False,
  1317. prev_sam_mask_logits=None,
  1318. )
  1319. return current_out["obj_ptr"]
  1320. def _run_memory_encoder(self, batch_size, high_res_masks, object_score_logits, is_mask_from_pts):
  1321. """
  1322. Run the memory encoder on masks.
  1323. This is usually after applying non-overlapping constraints to object scores. Since their scores changed, their
  1324. memory also needs to be computed again with the memory encoder.
  1325. Args:
  1326. batch_size (int): The batch size for processing the frame.
  1327. high_res_masks (torch.Tensor): High-resolution masks for which to compute the memory.
  1328. object_score_logits (torch.Tensor): Logits representing the object scores.
  1329. is_mask_from_pts (bool): Indicates if the mask is derived from point interactions.
  1330. Returns:
  1331. (tuple[torch.Tensor, torch.Tensor]): A tuple containing the encoded mask features and positional encoding.
  1332. """
  1333. # Retrieve correct image features
  1334. current_vision_feats, _, feat_sizes = self.get_im_features(self.inference_state["im"], batch_size)
  1335. maskmem_features, maskmem_pos_enc = self.model._encode_new_memory(
  1336. current_vision_feats=current_vision_feats,
  1337. feat_sizes=feat_sizes,
  1338. pred_masks_high_res=high_res_masks,
  1339. is_mask_from_pts=is_mask_from_pts,
  1340. object_score_logits=object_score_logits,
  1341. )
  1342. # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
  1343. maskmem_pos_enc = self._get_maskmem_pos_enc(maskmem_pos_enc)
  1344. return maskmem_features.to(dtype=torch.float16, device=self.device, non_blocking=True), maskmem_pos_enc
  1345. def _add_output_per_object(self, frame_idx, current_out, storage_key):
  1346. """
  1347. Split a multi-object output into per-object output slices and add them into Output_Dict_Per_Obj.
  1348. The resulting slices share the same tensor storage.
  1349. Args:
  1350. frame_idx (int): The index of the current frame.
  1351. current_out (Dict): The current output dictionary containing multi-object outputs.
  1352. storage_key (str): The key used to store the output in the per-object output dictionary.
  1353. """
  1354. maskmem_features = current_out["maskmem_features"]
  1355. assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor)
  1356. maskmem_pos_enc = current_out["maskmem_pos_enc"]
  1357. assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list)
  1358. for obj_idx, obj_output_dict in self.inference_state["output_dict_per_obj"].items():
  1359. obj_slice = slice(obj_idx, obj_idx + 1)
  1360. obj_out = {
  1361. "maskmem_features": None,
  1362. "maskmem_pos_enc": None,
  1363. "pred_masks": current_out["pred_masks"][obj_slice],
  1364. "obj_ptr": current_out["obj_ptr"][obj_slice],
  1365. }
  1366. if maskmem_features is not None:
  1367. obj_out["maskmem_features"] = maskmem_features[obj_slice]
  1368. if maskmem_pos_enc is not None:
  1369. obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc]
  1370. obj_output_dict[storage_key][frame_idx] = obj_out
  1371. def _clear_non_cond_mem_around_input(self, frame_idx):
  1372. """
  1373. Remove the non-conditioning memory around the input frame.
  1374. When users provide correction clicks, the surrounding frames' non-conditioning memories can still contain outdated
  1375. object appearance information and could confuse the model. This method clears those non-conditioning memories
  1376. surrounding the interacted frame to avoid giving the model both old and new information about the object.
  1377. Args:
  1378. frame_idx (int): The index of the current frame where user interaction occurred.
  1379. """
  1380. r = self.model.memory_temporal_stride_for_eval
  1381. frame_idx_begin = frame_idx - r * self.model.num_maskmem
  1382. frame_idx_end = frame_idx + r * self.model.num_maskmem
  1383. for t in range(frame_idx_begin, frame_idx_end + 1):
  1384. self.inference_state["output_dict"]["non_cond_frame_outputs"].pop(t, None)
  1385. for obj_output_dict in self.inference_state["output_dict_per_obj"].values():
  1386. obj_output_dict["non_cond_frame_outputs"].pop(t, None)