sam2_image_predictor.py 19 KB

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