automatic_mask_generator.py 15 KB

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