sam1_task_predictor.py 19 KB

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