sam2_image_predictor.py 19 KB

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