amg.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import math
  3. from itertools import product
  4. from typing import Any, Generator, List, Tuple
  5. import numpy as np
  6. import torch
  7. def is_box_near_crop_edge(
  8. boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0
  9. ) -> torch.Tensor:
  10. """Return a boolean tensor indicating if boxes are near the crop edge."""
  11. crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device)
  12. orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device)
  13. boxes = uncrop_boxes_xyxy(boxes, crop_box).float()
  14. near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0)
  15. near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0)
  16. near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge)
  17. return torch.any(near_crop_edge, dim=1)
  18. def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]:
  19. """Yield batches of data from the input arguments."""
  20. assert args and all(len(a) == len(args[0]) for a in args), "Batched iteration must have same-size inputs."
  21. n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0)
  22. for b in range(n_batches):
  23. yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args]
  24. def calculate_stability_score(masks: torch.Tensor, mask_threshold: float, threshold_offset: float) -> torch.Tensor:
  25. """
  26. Computes the stability score for a batch of masks.
  27. The stability score is the IoU between the binary masks obtained by thresholding the predicted mask logits at high
  28. and low values.
  29. Notes:
  30. - One mask is always contained inside the other.
  31. - Save memory by preventing unnecessary cast to torch.int64
  32. """
  33. intersections = (masks > (mask_threshold + threshold_offset)).sum(-1, dtype=torch.int16).sum(-1, dtype=torch.int32)
  34. unions = (masks > (mask_threshold - threshold_offset)).sum(-1, dtype=torch.int16).sum(-1, dtype=torch.int32)
  35. return intersections / unions
  36. def build_point_grid(n_per_side: int) -> np.ndarray:
  37. """Generate a 2D grid of evenly spaced points in the range [0,1]x[0,1]."""
  38. offset = 1 / (2 * n_per_side)
  39. points_one_side = np.linspace(offset, 1 - offset, n_per_side)
  40. points_x = np.tile(points_one_side[None, :], (n_per_side, 1))
  41. points_y = np.tile(points_one_side[:, None], (1, n_per_side))
  42. return np.stack([points_x, points_y], axis=-1).reshape(-1, 2)
  43. def build_all_layer_point_grids(n_per_side: int, n_layers: int, scale_per_layer: int) -> List[np.ndarray]:
  44. """Generate point grids for all crop layers."""
  45. return [build_point_grid(int(n_per_side / (scale_per_layer**i))) for i in range(n_layers + 1)]
  46. def generate_crop_boxes(
  47. im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float
  48. ) -> Tuple[List[List[int]], List[int]]:
  49. """
  50. Generates a list of crop boxes of different sizes.
  51. Each layer has (2**i)**2 boxes for the ith layer.
  52. """
  53. crop_boxes, layer_idxs = [], []
  54. im_h, im_w = im_size
  55. short_side = min(im_h, im_w)
  56. # Original image
  57. crop_boxes.append([0, 0, im_w, im_h])
  58. layer_idxs.append(0)
  59. def crop_len(orig_len, n_crops, overlap):
  60. """Crops bounding boxes to the size of the input image."""
  61. return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops))
  62. for i_layer in range(n_layers):
  63. n_crops_per_side = 2 ** (i_layer + 1)
  64. overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side))
  65. crop_w = crop_len(im_w, n_crops_per_side, overlap)
  66. crop_h = crop_len(im_h, n_crops_per_side, overlap)
  67. crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)]
  68. crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)]
  69. # Crops in XYWH format
  70. for x0, y0 in product(crop_box_x0, crop_box_y0):
  71. box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)]
  72. crop_boxes.append(box)
  73. layer_idxs.append(i_layer + 1)
  74. return crop_boxes, layer_idxs
  75. def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
  76. """Uncrop bounding boxes by adding the crop box offset."""
  77. x0, y0, _, _ = crop_box
  78. offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device)
  79. # Check if boxes has a channel dimension
  80. if len(boxes.shape) == 3:
  81. offset = offset.unsqueeze(1)
  82. return boxes + offset
  83. def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
  84. """Uncrop points by adding the crop box offset."""
  85. x0, y0, _, _ = crop_box
  86. offset = torch.tensor([[x0, y0]], device=points.device)
  87. # Check if points has a channel dimension
  88. if len(points.shape) == 3:
  89. offset = offset.unsqueeze(1)
  90. return points + offset
  91. def uncrop_masks(masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int) -> torch.Tensor:
  92. """Uncrop masks by padding them to the original image size."""
  93. x0, y0, x1, y1 = crop_box
  94. if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h:
  95. return masks
  96. # Coordinate transform masks
  97. pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0)
  98. pad = (x0, pad_x - x0, y0, pad_y - y0)
  99. return torch.nn.functional.pad(masks, pad, value=0)
  100. def remove_small_regions(mask: np.ndarray, area_thresh: float, mode: str) -> Tuple[np.ndarray, bool]:
  101. """Remove small disconnected regions or holes in a mask, returning the mask and a modification indicator."""
  102. import cv2 # type: ignore
  103. assert mode in {"holes", "islands"}, f"Provided mode {mode} is invalid"
  104. correct_holes = mode == "holes"
  105. working_mask = (correct_holes ^ mask).astype(np.uint8)
  106. n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8)
  107. sizes = stats[:, -1][1:] # Row 0 is background label
  108. small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh]
  109. if not small_regions:
  110. return mask, False
  111. fill_labels = [0] + small_regions
  112. if not correct_holes:
  113. # If every region is below threshold, keep largest
  114. fill_labels = [i for i in range(n_labels) if i not in fill_labels] or [int(np.argmax(sizes)) + 1]
  115. mask = np.isin(regions, fill_labels)
  116. return mask, True
  117. def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor:
  118. """
  119. Calculates boxes in XYXY format around masks.
  120. Return [0,0,0,0] for an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.
  121. """
  122. # torch.max below raises an error on empty inputs, just skip in this case
  123. if torch.numel(masks) == 0:
  124. return torch.zeros(*masks.shape[:-2], 4, device=masks.device)
  125. # Normalize shape to CxHxW
  126. shape = masks.shape
  127. h, w = shape[-2:]
  128. masks = masks.flatten(0, -3) if len(shape) > 2 else masks.unsqueeze(0)
  129. # Get top and bottom edges
  130. in_height, _ = torch.max(masks, dim=-1)
  131. in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :]
  132. bottom_edges, _ = torch.max(in_height_coords, dim=-1)
  133. in_height_coords = in_height_coords + h * (~in_height)
  134. top_edges, _ = torch.min(in_height_coords, dim=-1)
  135. # Get left and right edges
  136. in_width, _ = torch.max(masks, dim=-2)
  137. in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :]
  138. right_edges, _ = torch.max(in_width_coords, dim=-1)
  139. in_width_coords = in_width_coords + w * (~in_width)
  140. left_edges, _ = torch.min(in_width_coords, dim=-1)
  141. # If the mask is empty the right edge will be to the left of the left edge.
  142. # Replace these boxes with [0, 0, 0, 0]
  143. empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)
  144. out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1)
  145. out = out * (~empty_filter).unsqueeze(-1)
  146. # Return to original shape
  147. return out.reshape(*shape[:-2], 4) if len(shape) > 2 else out[0]