sam2_image_predictor.py 19 KB

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