amg.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. import math
  8. from copy import deepcopy
  9. from itertools import product
  10. from typing import Any, Dict, Generator, ItemsView, List, Tuple
  11. class MaskData:
  12. """
  13. A structure for storing masks and their related data in batched format.
  14. Implements basic filtering and concatenation.
  15. """
  16. def __init__(self, **kwargs) -> None:
  17. for v in kwargs.values():
  18. assert isinstance(
  19. v, (list, np.ndarray, torch.Tensor)
  20. ), "MaskData only supports list, numpy arrays, and torch tensors."
  21. self._stats = dict(**kwargs)
  22. def __setitem__(self, key: str, item: Any) -> None:
  23. assert isinstance(
  24. item, (list, np.ndarray, torch.Tensor)
  25. ), "MaskData only supports list, numpy arrays, and torch tensors."
  26. self._stats[key] = item
  27. def __delitem__(self, key: str) -> None:
  28. del self._stats[key]
  29. def __getitem__(self, key: str) -> Any:
  30. return self._stats[key]
  31. def items(self) -> ItemsView[str, Any]:
  32. return self._stats.items()
  33. def filter(self, keep: torch.Tensor) -> None:
  34. for k, v in self._stats.items():
  35. if v is None:
  36. self._stats[k] = None
  37. elif isinstance(v, torch.Tensor):
  38. self._stats[k] = v[torch.as_tensor(keep, device=v.device)]
  39. elif isinstance(v, np.ndarray):
  40. self._stats[k] = v[keep.detach().cpu().numpy()]
  41. elif isinstance(v, list) and keep.dtype == torch.bool:
  42. self._stats[k] = [a for i, a in enumerate(v) if keep[i]]
  43. elif isinstance(v, list):
  44. self._stats[k] = [v[i] for i in keep]
  45. else:
  46. raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.")
  47. def cat(self, new_stats: "MaskData") -> None:
  48. for k, v in new_stats.items():
  49. if k not in self._stats or self._stats[k] is None:
  50. self._stats[k] = deepcopy(v)
  51. elif isinstance(v, torch.Tensor):
  52. self._stats[k] = torch.cat([self._stats[k], v], dim=0)
  53. elif isinstance(v, np.ndarray):
  54. self._stats[k] = np.concatenate([self._stats[k], v], axis=0)
  55. elif isinstance(v, list):
  56. self._stats[k] = self._stats[k] + deepcopy(v)
  57. else:
  58. raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.")
  59. def to_numpy(self) -> None:
  60. for k, v in self._stats.items():
  61. if isinstance(v, torch.Tensor):
  62. self._stats[k] = v.detach().cpu().numpy()
  63. def is_box_near_crop_edge(
  64. boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0
  65. ) -> torch.Tensor:
  66. """Filter masks at the edge of a crop, but not at the edge of the original image."""
  67. crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device)
  68. orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device)
  69. boxes = uncrop_boxes_xyxy(boxes, crop_box).float()
  70. near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0)
  71. near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0)
  72. near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge)
  73. return torch.any(near_crop_edge, dim=1)
  74. def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor:
  75. box_xywh = deepcopy(box_xyxy)
  76. box_xywh[2] = box_xywh[2] - box_xywh[0]
  77. box_xywh[3] = box_xywh[3] - box_xywh[1]
  78. return box_xywh
  79. def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]:
  80. assert len(args) > 0 and all(
  81. len(a) == len(args[0]) for a in args
  82. ), "Batched iteration must have inputs of all the same size."
  83. n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0)
  84. for b in range(n_batches):
  85. yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args]
  86. def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]:
  87. """
  88. Encodes masks to an uncompressed RLE, in the format expected by
  89. pycoco tools.
  90. """
  91. # Put in fortran order and flatten h,w
  92. b, h, w = tensor.shape
  93. tensor = tensor.permute(0, 2, 1).flatten(1)
  94. # Compute change indices
  95. diff = tensor[:, 1:] ^ tensor[:, :-1]
  96. change_indices = diff.nonzero()
  97. # Encode run length
  98. out = []
  99. for i in range(b):
  100. cur_idxs = change_indices[change_indices[:, 0] == i, 1]
  101. cur_idxs = torch.cat(
  102. [
  103. torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device),
  104. cur_idxs + 1,
  105. torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device),
  106. ]
  107. )
  108. btw_idxs = cur_idxs[1:] - cur_idxs[:-1]
  109. counts = [] if tensor[i, 0] == 0 else [0]
  110. counts.extend(btw_idxs.detach().cpu().tolist())
  111. out.append({"size": [h, w], "counts": counts})
  112. return out
  113. def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray:
  114. """Compute a binary mask from an uncompressed RLE."""
  115. h, w = rle["size"]
  116. mask = np.empty(h * w, dtype=bool)
  117. idx = 0
  118. parity = False
  119. for count in rle["counts"]:
  120. mask[idx : idx + count] = parity
  121. idx += count
  122. parity ^= True
  123. mask = mask.reshape(w, h)
  124. return mask.transpose() # Put in C order
  125. def area_from_rle(rle: Dict[str, Any]) -> int:
  126. return sum(rle["counts"][1::2])
  127. def calculate_stability_score(
  128. masks: torch.Tensor, mask_threshold: float, threshold_offset: float
  129. ) -> torch.Tensor:
  130. """
  131. Computes the stability score for a batch of masks. The stability
  132. score is the IoU between the binary masks obtained by thresholding
  133. the predicted mask logits at high and low values.
  134. """
  135. # One mask is always contained inside the other.
  136. # Save memory by preventing unnecessary cast to torch.int64
  137. intersections = (
  138. (masks > (mask_threshold + threshold_offset))
  139. .sum(-1, dtype=torch.int16)
  140. .sum(-1, dtype=torch.int32)
  141. )
  142. unions = (
  143. (masks > (mask_threshold - threshold_offset))
  144. .sum(-1, dtype=torch.int16)
  145. .sum(-1, dtype=torch.int32)
  146. )
  147. return intersections / unions
  148. def build_point_grid(n_per_side: int) -> np.ndarray:
  149. """Generates a 2D grid of points evenly spaced in [0,1]x[0,1]."""
  150. offset = 1 / (2 * n_per_side)
  151. points_one_side = np.linspace(offset, 1 - offset, n_per_side)
  152. points_x = np.tile(points_one_side[None, :], (n_per_side, 1))
  153. points_y = np.tile(points_one_side[:, None], (1, n_per_side))
  154. points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2)
  155. return points
  156. def build_all_layer_point_grids(
  157. n_per_side: int, n_layers: int, scale_per_layer: int
  158. ) -> List[np.ndarray]:
  159. """Generates point grids for all crop layers."""
  160. points_by_layer = []
  161. for i in range(n_layers + 1):
  162. n_points = int(n_per_side / (scale_per_layer**i))
  163. points_by_layer.append(build_point_grid(n_points))
  164. return points_by_layer
  165. def generate_crop_boxes(
  166. im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float
  167. ) -> Tuple[List[List[int]], List[int]]:
  168. """
  169. Generates a list of crop boxes of different sizes. Each layer
  170. has (2**i)**2 boxes for the ith layer.
  171. """
  172. crop_boxes, layer_idxs = [], []
  173. im_h, im_w = im_size
  174. short_side = min(im_h, im_w)
  175. # Original image
  176. crop_boxes.append([0, 0, im_w, im_h])
  177. layer_idxs.append(0)
  178. def crop_len(orig_len, n_crops, overlap):
  179. return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops))
  180. for i_layer in range(n_layers):
  181. n_crops_per_side = 2 ** (i_layer + 1)
  182. overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side))
  183. crop_w = crop_len(im_w, n_crops_per_side, overlap)
  184. crop_h = crop_len(im_h, n_crops_per_side, overlap)
  185. crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)]
  186. crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)]
  187. # Crops in XYWH format
  188. for x0, y0 in product(crop_box_x0, crop_box_y0):
  189. box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)]
  190. crop_boxes.append(box)
  191. layer_idxs.append(i_layer + 1)
  192. return crop_boxes, layer_idxs
  193. def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
  194. x0, y0, _, _ = crop_box
  195. offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device)
  196. # Check if boxes has a channel dimension
  197. if len(boxes.shape) == 3:
  198. offset = offset.unsqueeze(1)
  199. return boxes + offset
  200. def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
  201. x0, y0, _, _ = crop_box
  202. offset = torch.tensor([[x0, y0]], device=points.device)
  203. # Check if points has a channel dimension
  204. if len(points.shape) == 3:
  205. offset = offset.unsqueeze(1)
  206. return points + offset
  207. def uncrop_masks(
  208. masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int
  209. ) -> torch.Tensor:
  210. x0, y0, x1, y1 = crop_box
  211. if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h:
  212. return masks
  213. # Coordinate transform masks
  214. pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0)
  215. pad = (x0, pad_x - x0, y0, pad_y - y0)
  216. return torch.nn.functional.pad(masks, pad, value=0)
  217. def remove_small_regions(
  218. mask: np.ndarray, area_thresh: float, mode: str
  219. ) -> Tuple[np.ndarray, bool]:
  220. """
  221. Removes small disconnected regions and holes in a mask. Returns the
  222. mask and an indicator of if the mask has been modified.
  223. """
  224. import cv2 # type: ignore
  225. assert mode in ["holes", "islands"]
  226. correct_holes = mode == "holes"
  227. working_mask = (correct_holes ^ mask).astype(np.uint8)
  228. n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8)
  229. sizes = stats[:, -1][1:] # Row 0 is background label
  230. small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh]
  231. if len(small_regions) == 0:
  232. return mask, False
  233. fill_labels = [0] + small_regions
  234. if not correct_holes:
  235. fill_labels = [i for i in range(n_labels) if i not in fill_labels]
  236. # If every region is below threshold, keep largest
  237. if len(fill_labels) == 0:
  238. fill_labels = [int(np.argmax(sizes)) + 1]
  239. mask = np.isin(regions, fill_labels)
  240. return mask, True
  241. def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]:
  242. from pycocotools import mask as mask_utils # type: ignore
  243. h, w = uncompressed_rle["size"]
  244. rle = mask_utils.frPyObjects(uncompressed_rle, h, w)
  245. rle["counts"] = rle["counts"].decode("utf-8") # Necessary to serialize with json
  246. return rle
  247. def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor:
  248. """
  249. Calculates boxes in XYXY format around masks. Return [0,0,0,0] for
  250. an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.
  251. """
  252. # torch.max below raises an error on empty inputs, just skip in this case
  253. if torch.numel(masks) == 0:
  254. return torch.zeros(*masks.shape[:-2], 4, device=masks.device)
  255. # Normalize shape to CxHxW
  256. shape = masks.shape
  257. h, w = shape[-2:]
  258. if len(shape) > 2:
  259. masks = masks.flatten(0, -3)
  260. else:
  261. masks = masks.unsqueeze(0)
  262. # Get top and bottom edges
  263. in_height, _ = torch.max(masks, dim=-1)
  264. in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :]
  265. bottom_edges, _ = torch.max(in_height_coords, dim=-1)
  266. in_height_coords = in_height_coords + h * (~in_height)
  267. top_edges, _ = torch.min(in_height_coords, dim=-1)
  268. # Get left and right edges
  269. in_width, _ = torch.max(masks, dim=-2)
  270. in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :]
  271. right_edges, _ = torch.max(in_width_coords, dim=-1)
  272. in_width_coords = in_width_coords + w * (~in_width)
  273. left_edges, _ = torch.min(in_width_coords, dim=-1)
  274. # If the mask is empty the right edge will be to the left of the left edge.
  275. # Replace these boxes with [0, 0, 0, 0]
  276. empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)
  277. out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1)
  278. out = out * (~empty_filter).unsqueeze(-1)
  279. # Return to original shape
  280. if len(shape) > 2:
  281. out = out.reshape(*shape[:-2], 4)
  282. else:
  283. out = out[0]
  284. return out