automatic_mask_generator.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. # Adapted from https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/automatic_mask_generator.py
  6. from typing import Any, Dict, List, Optional, Tuple
  7. import numpy as np
  8. import torch
  9. from torchvision.ops.boxes import batched_nms, box_area # type: ignore
  10. from sam2.modeling.sam2_base import SAM2Base
  11. from sam2.sam2_image_predictor import SAM2ImagePredictor
  12. from sam2.utils.amg import (
  13. area_from_rle,
  14. batch_iterator,
  15. batched_mask_to_box,
  16. box_xyxy_to_xywh,
  17. build_all_layer_point_grids,
  18. calculate_stability_score,
  19. coco_encode_rle,
  20. generate_crop_boxes,
  21. is_box_near_crop_edge,
  22. mask_to_rle_pytorch,
  23. MaskData,
  24. remove_small_regions,
  25. rle_to_mask,
  26. uncrop_boxes_xyxy,
  27. uncrop_masks,
  28. uncrop_points,
  29. )
  30. class SAM2AutomaticMaskGenerator:
  31. def __init__(
  32. self,
  33. model: SAM2Base,
  34. points_per_side: Optional[int] = 32,
  35. points_per_batch: int = 64,
  36. pred_iou_thresh: float = 0.8,
  37. stability_score_thresh: float = 0.95,
  38. stability_score_offset: float = 1.0,
  39. mask_threshold: float = 0.0,
  40. box_nms_thresh: float = 0.7,
  41. crop_n_layers: int = 0,
  42. crop_nms_thresh: float = 0.7,
  43. crop_overlap_ratio: float = 512 / 1500,
  44. crop_n_points_downscale_factor: int = 1,
  45. point_grids: Optional[List[np.ndarray]] = None,
  46. min_mask_region_area: int = 0,
  47. output_mode: str = "binary_mask",
  48. use_m2m: bool = False,
  49. multimask_output: bool = True,
  50. ) -> None:
  51. """
  52. Using a SAM 2 model, generates masks for the entire image.
  53. Generates a grid of point prompts over the image, then filters
  54. low quality and duplicate masks. The default settings are chosen
  55. for SAM 2 with a HieraL backbone.
  56. Arguments:
  57. model (Sam): The SAM 2 model to use for mask prediction.
  58. points_per_side (int or None): The number of points to be sampled
  59. along one side of the image. The total number of points is
  60. points_per_side**2. If None, 'point_grids' must provide explicit
  61. point sampling.
  62. points_per_batch (int): Sets the number of points run simultaneously
  63. by the model. Higher numbers may be faster but use more GPU memory.
  64. pred_iou_thresh (float): A filtering threshold in [0,1], using the
  65. model's predicted mask quality.
  66. stability_score_thresh (float): A filtering threshold in [0,1], using
  67. the stability of the mask under changes to the cutoff used to binarize
  68. the model's mask predictions.
  69. stability_score_offset (float): The amount to shift the cutoff when
  70. calculated the stability score.
  71. mask_threshold (float): Threshold for binarizing the mask logits
  72. box_nms_thresh (float): The box IoU cutoff used by non-maximal
  73. suppression to filter duplicate masks.
  74. crop_n_layers (int): If >0, mask prediction will be run again on
  75. crops of the image. Sets the number of layers to run, where each
  76. layer has 2**i_layer number of image crops.
  77. crop_nms_thresh (float): The box IoU cutoff used by non-maximal
  78. suppression to filter duplicate masks between different crops.
  79. crop_overlap_ratio (float): Sets the degree to which crops overlap.
  80. In the first crop layer, crops will overlap by this fraction of
  81. the image length. Later layers with more crops scale down this overlap.
  82. crop_n_points_downscale_factor (int): The number of points-per-side
  83. sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
  84. point_grids (list(np.ndarray) or None): A list over explicit grids
  85. of points used for sampling, normalized to [0,1]. The nth grid in the
  86. list is used in the nth crop layer. Exclusive with points_per_side.
  87. min_mask_region_area (int): If >0, postprocessing will be applied
  88. to remove disconnected regions and holes in masks with area smaller
  89. than min_mask_region_area. Requires opencv.
  90. output_mode (str): The form masks are returned in. Can be 'binary_mask',
  91. 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools.
  92. For large resolutions, 'binary_mask' may consume large amounts of
  93. memory.
  94. use_m2m (bool): Whether to add a one step refinement using previous mask predictions.
  95. multimask_output (bool): Whether to output multimask at each point of the grid.
  96. """
  97. assert (points_per_side is None) != (
  98. point_grids is None
  99. ), "Exactly one of points_per_side or point_grid must be provided."
  100. if points_per_side is not None:
  101. self.point_grids = build_all_layer_point_grids(
  102. points_per_side,
  103. crop_n_layers,
  104. crop_n_points_downscale_factor,
  105. )
  106. elif point_grids is not None:
  107. self.point_grids = point_grids
  108. else:
  109. raise ValueError("Can't have both points_per_side and point_grid be None.")
  110. assert output_mode in [
  111. "binary_mask",
  112. "uncompressed_rle",
  113. "coco_rle",
  114. ], f"Unknown output_mode {output_mode}."
  115. if output_mode == "coco_rle":
  116. try:
  117. from pycocotools import mask as mask_utils # type: ignore # noqa: F401
  118. except ImportError as e:
  119. print("Please install pycocotools")
  120. raise e
  121. self.predictor = SAM2ImagePredictor(
  122. model,
  123. max_hole_area=min_mask_region_area,
  124. max_sprinkle_area=min_mask_region_area,
  125. )
  126. self.points_per_batch = points_per_batch
  127. self.pred_iou_thresh = pred_iou_thresh
  128. self.stability_score_thresh = stability_score_thresh
  129. self.stability_score_offset = stability_score_offset
  130. self.mask_threshold = mask_threshold
  131. self.box_nms_thresh = box_nms_thresh
  132. self.crop_n_layers = crop_n_layers
  133. self.crop_nms_thresh = crop_nms_thresh
  134. self.crop_overlap_ratio = crop_overlap_ratio
  135. self.crop_n_points_downscale_factor = crop_n_points_downscale_factor
  136. self.min_mask_region_area = min_mask_region_area
  137. self.output_mode = output_mode
  138. self.use_m2m = use_m2m
  139. self.multimask_output = multimask_output
  140. @torch.no_grad()
  141. def generate(self, image: np.ndarray) -> List[Dict[str, Any]]:
  142. """
  143. Generates masks for the given image.
  144. Arguments:
  145. image (np.ndarray): The image to generate masks for, in HWC uint8 format.
  146. Returns:
  147. list(dict(str, any)): A list over records for masks. Each record is
  148. a dict containing the following keys:
  149. segmentation (dict(str, any) or np.ndarray): The mask. If
  150. output_mode='binary_mask', is an array of shape HW. Otherwise,
  151. is a dictionary containing the RLE.
  152. bbox (list(float)): The box around the mask, in XYWH format.
  153. area (int): The area in pixels of the mask.
  154. predicted_iou (float): The model's own prediction of the mask's
  155. quality. This is filtered by the pred_iou_thresh parameter.
  156. point_coords (list(list(float))): The point coordinates input
  157. to the model to generate this mask.
  158. stability_score (float): A measure of the mask's quality. This
  159. is filtered on using the stability_score_thresh parameter.
  160. crop_box (list(float)): The crop of the image used to generate
  161. the mask, given in XYWH format.
  162. """
  163. # Generate masks
  164. mask_data = self._generate_masks(image)
  165. # Encode masks
  166. if self.output_mode == "coco_rle":
  167. mask_data["segmentations"] = [
  168. coco_encode_rle(rle) for rle in mask_data["rles"]
  169. ]
  170. elif self.output_mode == "binary_mask":
  171. mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]]
  172. else:
  173. mask_data["segmentations"] = mask_data["rles"]
  174. # Write mask records
  175. curr_anns = []
  176. for idx in range(len(mask_data["segmentations"])):
  177. ann = {
  178. "segmentation": mask_data["segmentations"][idx],
  179. "area": area_from_rle(mask_data["rles"][idx]),
  180. "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(),
  181. "predicted_iou": mask_data["iou_preds"][idx].item(),
  182. "point_coords": [mask_data["points"][idx].tolist()],
  183. "stability_score": mask_data["stability_score"][idx].item(),
  184. "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(),
  185. }
  186. curr_anns.append(ann)
  187. return curr_anns
  188. def _generate_masks(self, image: np.ndarray) -> MaskData:
  189. orig_size = image.shape[:2]
  190. crop_boxes, layer_idxs = generate_crop_boxes(
  191. orig_size, self.crop_n_layers, self.crop_overlap_ratio
  192. )
  193. # Iterate over image crops
  194. data = MaskData()
  195. for crop_box, layer_idx in zip(crop_boxes, layer_idxs):
  196. crop_data = self._process_crop(image, crop_box, layer_idx, orig_size)
  197. data.cat(crop_data)
  198. # Remove duplicate masks between crops
  199. if len(crop_boxes) > 1:
  200. # Prefer masks from smaller crops
  201. scores = 1 / box_area(data["crop_boxes"])
  202. scores = scores.to(data["boxes"].device)
  203. keep_by_nms = batched_nms(
  204. data["boxes"].float(),
  205. scores,
  206. torch.zeros_like(data["boxes"][:, 0]), # categories
  207. iou_threshold=self.crop_nms_thresh,
  208. )
  209. data.filter(keep_by_nms)
  210. data.to_numpy()
  211. return data
  212. def _process_crop(
  213. self,
  214. image: np.ndarray,
  215. crop_box: List[int],
  216. crop_layer_idx: int,
  217. orig_size: Tuple[int, ...],
  218. ) -> MaskData:
  219. # Crop the image and calculate embeddings
  220. x0, y0, x1, y1 = crop_box
  221. cropped_im = image[y0:y1, x0:x1, :]
  222. cropped_im_size = cropped_im.shape[:2]
  223. self.predictor.set_image(cropped_im)
  224. # Get points for this crop
  225. points_scale = np.array(cropped_im_size)[None, ::-1]
  226. points_for_image = self.point_grids[crop_layer_idx] * points_scale
  227. # Generate masks for this crop in batches
  228. data = MaskData()
  229. for (points,) in batch_iterator(self.points_per_batch, points_for_image):
  230. batch_data = self._process_batch(
  231. points, cropped_im_size, crop_box, orig_size, normalize=True
  232. )
  233. data.cat(batch_data)
  234. del batch_data
  235. self.predictor.reset_predictor()
  236. # Remove duplicates within this crop.
  237. keep_by_nms = batched_nms(
  238. data["boxes"].float(),
  239. data["iou_preds"],
  240. torch.zeros_like(data["boxes"][:, 0]), # categories
  241. iou_threshold=self.box_nms_thresh,
  242. )
  243. data.filter(keep_by_nms)
  244. # Return to the original image frame
  245. data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box)
  246. data["points"] = uncrop_points(data["points"], crop_box)
  247. data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))])
  248. return data
  249. def _process_batch(
  250. self,
  251. points: np.ndarray,
  252. im_size: Tuple[int, ...],
  253. crop_box: List[int],
  254. orig_size: Tuple[int, ...],
  255. normalize=False,
  256. ) -> MaskData:
  257. orig_h, orig_w = orig_size
  258. # Run model on this batch
  259. points = torch.as_tensor(
  260. points, dtype=torch.float32, device=self.predictor.device
  261. )
  262. in_points = self.predictor._transforms.transform_coords(
  263. points, normalize=normalize, orig_hw=im_size
  264. )
  265. in_labels = torch.ones(
  266. in_points.shape[0], dtype=torch.int, device=in_points.device
  267. )
  268. masks, iou_preds, low_res_masks = self.predictor._predict(
  269. in_points[:, None, :],
  270. in_labels[:, None],
  271. multimask_output=self.multimask_output,
  272. return_logits=True,
  273. )
  274. # Serialize predictions and store in MaskData
  275. data = MaskData(
  276. masks=masks.flatten(0, 1),
  277. iou_preds=iou_preds.flatten(0, 1),
  278. points=points.repeat_interleave(masks.shape[1], dim=0),
  279. low_res_masks=low_res_masks.flatten(0, 1),
  280. )
  281. del masks
  282. if not self.use_m2m:
  283. # Filter by predicted IoU
  284. if self.pred_iou_thresh > 0.0:
  285. keep_mask = data["iou_preds"] > self.pred_iou_thresh
  286. data.filter(keep_mask)
  287. # Calculate and filter by stability score
  288. data["stability_score"] = calculate_stability_score(
  289. data["masks"], self.mask_threshold, self.stability_score_offset
  290. )
  291. if self.stability_score_thresh > 0.0:
  292. keep_mask = data["stability_score"] >= self.stability_score_thresh
  293. data.filter(keep_mask)
  294. else:
  295. # One step refinement using previous mask predictions
  296. in_points = self.predictor._transforms.transform_coords(
  297. data["points"], normalize=normalize, orig_hw=im_size
  298. )
  299. labels = torch.ones(
  300. in_points.shape[0], dtype=torch.int, device=in_points.device
  301. )
  302. masks, ious = self.refine_with_m2m(
  303. in_points, labels, data["low_res_masks"], self.points_per_batch
  304. )
  305. data["masks"] = masks.squeeze(1)
  306. data["iou_preds"] = ious.squeeze(1)
  307. if self.pred_iou_thresh > 0.0:
  308. keep_mask = data["iou_preds"] > self.pred_iou_thresh
  309. data.filter(keep_mask)
  310. data["stability_score"] = calculate_stability_score(
  311. data["masks"], self.mask_threshold, self.stability_score_offset
  312. )
  313. if self.stability_score_thresh > 0.0:
  314. keep_mask = data["stability_score"] >= self.stability_score_thresh
  315. data.filter(keep_mask)
  316. # Threshold masks and calculate boxes
  317. data["masks"] = data["masks"] > self.mask_threshold
  318. data["boxes"] = batched_mask_to_box(data["masks"])
  319. # Filter boxes that touch crop boundaries
  320. keep_mask = ~is_box_near_crop_edge(
  321. data["boxes"], crop_box, [0, 0, orig_w, orig_h]
  322. )
  323. if not torch.all(keep_mask):
  324. data.filter(keep_mask)
  325. # Compress to RLE
  326. data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w)
  327. data["rles"] = mask_to_rle_pytorch(data["masks"])
  328. del data["masks"]
  329. return data
  330. @staticmethod
  331. def postprocess_small_regions(
  332. mask_data: MaskData, min_area: int, nms_thresh: float
  333. ) -> MaskData:
  334. """
  335. Removes small disconnected regions and holes in masks, then reruns
  336. box NMS to remove any new duplicates.
  337. Edits mask_data in place.
  338. Requires open-cv as a dependency.
  339. """
  340. if len(mask_data["rles"]) == 0:
  341. return mask_data
  342. # Filter small disconnected regions and holes
  343. new_masks = []
  344. scores = []
  345. for rle in mask_data["rles"]:
  346. mask = rle_to_mask(rle)
  347. mask, changed = remove_small_regions(mask, min_area, mode="holes")
  348. unchanged = not changed
  349. mask, changed = remove_small_regions(mask, min_area, mode="islands")
  350. unchanged = unchanged and not changed
  351. new_masks.append(torch.as_tensor(mask).unsqueeze(0))
  352. # Give score=0 to changed masks and score=1 to unchanged masks
  353. # so NMS will prefer ones that didn't need postprocessing
  354. scores.append(float(unchanged))
  355. # Recalculate boxes and remove any new duplicates
  356. masks = torch.cat(new_masks, dim=0)
  357. boxes = batched_mask_to_box(masks)
  358. keep_by_nms = batched_nms(
  359. boxes.float(),
  360. torch.as_tensor(scores),
  361. torch.zeros_like(boxes[:, 0]), # categories
  362. iou_threshold=nms_thresh,
  363. )
  364. # Only recalculate RLEs for masks that have changed
  365. for i_mask in keep_by_nms:
  366. if scores[i_mask] == 0.0:
  367. mask_torch = masks[i_mask].unsqueeze(0)
  368. mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0]
  369. mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly
  370. mask_data.filter(keep_by_nms)
  371. return mask_data
  372. def refine_with_m2m(self, points, point_labels, low_res_masks, points_per_batch):
  373. new_masks = []
  374. new_iou_preds = []
  375. for cur_points, cur_point_labels, low_res_mask in batch_iterator(
  376. points_per_batch, points, point_labels, low_res_masks
  377. ):
  378. best_masks, best_iou_preds, _ = self.predictor._predict(
  379. cur_points[:, None, :],
  380. cur_point_labels[:, None],
  381. mask_input=low_res_mask[:, None, :],
  382. multimask_output=False,
  383. return_logits=True,
  384. )
  385. new_masks.append(best_masks)
  386. new_iou_preds.append(best_iou_preds)
  387. masks = torch.cat(new_masks, dim=0)
  388. return masks, torch.cat(new_iou_preds, dim=0)