sam2_image_predictor.py 19 KB

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