rotated_boxes.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
  2. # pyre-unsafe
  3. from __future__ import absolute_import, division, print_function, unicode_literals
  4. import math
  5. from typing import List, Tuple
  6. import torch
  7. # from detectron2.layers.rotated_boxes import pairwise_iou_rotated
  8. from .boxes import Boxes
  9. def pairwise_iou_rotated(boxes1, boxes2):
  10. """
  11. Return intersection-over-union (Jaccard index) of boxes.
  12. Both sets of boxes are expected to be in
  13. (x_center, y_center, width, height, angle) format.
  14. Arguments:
  15. boxes1 (Tensor[N, 5])
  16. boxes2 (Tensor[M, 5])
  17. Returns:
  18. iou (Tensor[N, M]): the NxM matrix containing the pairwise
  19. IoU values for every element in boxes1 and boxes2
  20. """
  21. return torch.ops.detectron2.box_iou_rotated(boxes1, boxes2)
  22. class RotatedBoxes(Boxes):
  23. """
  24. This structure stores a list of rotated boxes as a Nx5 torch.Tensor.
  25. It supports some common methods about boxes
  26. (`area`, `clip`, `nonempty`, etc),
  27. and also behaves like a Tensor
  28. (support indexing, `to(device)`, `.device`, and iteration over all boxes)
  29. """
  30. def __init__(self, tensor: torch.Tensor):
  31. """
  32. Args:
  33. tensor (Tensor[float]): a Nx5 matrix. Each row is
  34. (x_center, y_center, width, height, angle),
  35. in which angle is represented in degrees.
  36. While there's no strict range restriction for it,
  37. the recommended principal range is between [-180, 180) degrees.
  38. Assume we have a horizontal box B = (x_center, y_center, width, height),
  39. where width is along the x-axis and height is along the y-axis.
  40. The rotated box B_rot (x_center, y_center, width, height, angle)
  41. can be seen as:
  42. 1. When angle == 0:
  43. B_rot == B
  44. 2. When angle > 0:
  45. B_rot is obtained by rotating B w.r.t its center by :math:`|angle|` degrees CCW;
  46. 3. When angle < 0:
  47. B_rot is obtained by rotating B w.r.t its center by :math:`|angle|` degrees CW.
  48. Mathematically, since the right-handed coordinate system for image space
  49. is (y, x), where y is top->down and x is left->right, the 4 vertices of the
  50. rotated rectangle :math:`(yr_i, xr_i)` (i = 1, 2, 3, 4) can be obtained from
  51. the vertices of the horizontal rectangle :math:`(y_i, x_i)` (i = 1, 2, 3, 4)
  52. in the following way (:math:`\\theta = angle*\\pi/180` is the angle in radians,
  53. :math:`(y_c, x_c)` is the center of the rectangle):
  54. .. math::
  55. yr_i = \\cos(\\theta) (y_i - y_c) - \\sin(\\theta) (x_i - x_c) + y_c,
  56. xr_i = \\sin(\\theta) (y_i - y_c) + \\cos(\\theta) (x_i - x_c) + x_c,
  57. which is the standard rigid-body rotation transformation.
  58. Intuitively, the angle is
  59. (1) the rotation angle from y-axis in image space
  60. to the height vector (top->down in the box's local coordinate system)
  61. of the box in CCW, and
  62. (2) the rotation angle from x-axis in image space
  63. to the width vector (left->right in the box's local coordinate system)
  64. of the box in CCW.
  65. More intuitively, consider the following horizontal box ABCD represented
  66. in (x1, y1, x2, y2): (3, 2, 7, 4),
  67. covering the [3, 7] x [2, 4] region of the continuous coordinate system
  68. which looks like this:
  69. .. code:: none
  70. O--------> x
  71. |
  72. | A---B
  73. | | |
  74. | D---C
  75. |
  76. v y
  77. Note that each capital letter represents one 0-dimensional geometric point
  78. instead of a 'square pixel' here.
  79. In the example above, using (x, y) to represent a point we have:
  80. .. math::
  81. O = (0, 0), A = (3, 2), B = (7, 2), C = (7, 4), D = (3, 4)
  82. We name vector AB = vector DC as the width vector in box's local coordinate system, and
  83. vector AD = vector BC as the height vector in box's local coordinate system. Initially,
  84. when angle = 0 degree, they're aligned with the positive directions of x-axis and y-axis
  85. in the image space, respectively.
  86. For better illustration, we denote the center of the box as E,
  87. .. code:: none
  88. O--------> x
  89. |
  90. | A---B
  91. | | E |
  92. | D---C
  93. |
  94. v y
  95. where the center E = ((3+7)/2, (2+4)/2) = (5, 3).
  96. Also,
  97. .. math::
  98. width = |AB| = |CD| = 7 - 3 = 4,
  99. height = |AD| = |BC| = 4 - 2 = 2.
  100. Therefore, the corresponding representation for the same shape in rotated box in
  101. (x_center, y_center, width, height, angle) format is:
  102. (5, 3, 4, 2, 0),
  103. Now, let's consider (5, 3, 4, 2, 90), which is rotated by 90 degrees
  104. CCW (counter-clockwise) by definition. It looks like this:
  105. .. code:: none
  106. O--------> x
  107. | B-C
  108. | | |
  109. | |E|
  110. | | |
  111. | A-D
  112. v y
  113. The center E is still located at the same point (5, 3), while the vertices
  114. ABCD are rotated by 90 degrees CCW with regard to E:
  115. A = (4, 5), B = (4, 1), C = (6, 1), D = (6, 5)
  116. Here, 90 degrees can be seen as the CCW angle to rotate from y-axis to
  117. vector AD or vector BC (the top->down height vector in box's local coordinate system),
  118. or the CCW angle to rotate from x-axis to vector AB or vector DC (the left->right
  119. width vector in box's local coordinate system).
  120. .. math::
  121. width = |AB| = |CD| = 5 - 1 = 4,
  122. height = |AD| = |BC| = 6 - 4 = 2.
  123. Next, how about (5, 3, 4, 2, -90), which is rotated by 90 degrees CW (clockwise)
  124. by definition? It looks like this:
  125. .. code:: none
  126. O--------> x
  127. | D-A
  128. | | |
  129. | |E|
  130. | | |
  131. | C-B
  132. v y
  133. The center E is still located at the same point (5, 3), while the vertices
  134. ABCD are rotated by 90 degrees CW with regard to E:
  135. A = (6, 1), B = (6, 5), C = (4, 5), D = (4, 1)
  136. .. math::
  137. width = |AB| = |CD| = 5 - 1 = 4,
  138. height = |AD| = |BC| = 6 - 4 = 2.
  139. This covers exactly the same region as (5, 3, 4, 2, 90) does, and their IoU
  140. will be 1. However, these two will generate different RoI Pooling results and
  141. should not be treated as an identical box.
  142. On the other hand, it's easy to see that (X, Y, W, H, A) is identical to
  143. (X, Y, W, H, A+360N), for any integer N. For example (5, 3, 4, 2, 270) would be
  144. identical to (5, 3, 4, 2, -90), because rotating the shape 270 degrees CCW is
  145. equivalent to rotating the same shape 90 degrees CW.
  146. We could rotate further to get (5, 3, 4, 2, 180), or (5, 3, 4, 2, -180):
  147. .. code:: none
  148. O--------> x
  149. |
  150. | C---D
  151. | | E |
  152. | B---A
  153. |
  154. v y
  155. .. math::
  156. A = (7, 4), B = (3, 4), C = (3, 2), D = (7, 2),
  157. width = |AB| = |CD| = 7 - 3 = 4,
  158. height = |AD| = |BC| = 4 - 2 = 2.
  159. Finally, this is a very inaccurate (heavily quantized) illustration of
  160. how (5, 3, 4, 2, 60) looks like in case anyone wonders:
  161. .. code:: none
  162. O--------> x
  163. | B\
  164. | / C
  165. | /E /
  166. | A /
  167. | `D
  168. v y
  169. It's still a rectangle with center of (5, 3), width of 4 and height of 2,
  170. but its angle (and thus orientation) is somewhere between
  171. (5, 3, 4, 2, 0) and (5, 3, 4, 2, 90).
  172. """
  173. device = (
  174. tensor.device if isinstance(tensor, torch.Tensor) else torch.device("cpu")
  175. )
  176. tensor = torch.as_tensor(tensor, dtype=torch.float32, device=device)
  177. if tensor.numel() == 0:
  178. # Use reshape, so we don't end up creating a new tensor that does not depend on
  179. # the inputs (and consequently confuses jit)
  180. tensor = tensor.reshape((0, 5)).to(dtype=torch.float32, device=device)
  181. assert tensor.dim() == 2 and tensor.size(-1) == 5, tensor.size()
  182. self.tensor = tensor
  183. def clone(self) -> "RotatedBoxes":
  184. """
  185. Clone the RotatedBoxes.
  186. Returns:
  187. RotatedBoxes
  188. """
  189. return RotatedBoxes(self.tensor.clone())
  190. def to(self, device: torch.device, non_blocking: bool = False):
  191. # Boxes are assumed float32 and does not support to(dtype)
  192. return RotatedBoxes(self.tensor.to(device=device, non_blocking=non_blocking))
  193. def area(self) -> torch.Tensor:
  194. """
  195. Computes the area of all the boxes.
  196. Returns:
  197. torch.Tensor: a vector with areas of each box.
  198. """
  199. box = self.tensor
  200. area = box[:, 2] * box[:, 3]
  201. return area
  202. # Avoid in-place operations so that we can torchscript; NOTE: this creates a new tensor
  203. def normalize_angles(self) -> None:
  204. """
  205. Restrict angles to the range of [-180, 180) degrees
  206. """
  207. angle_tensor = (self.tensor[:, 4] + 180.0) % 360.0 - 180.0
  208. self.tensor = torch.cat((self.tensor[:, :4], angle_tensor[:, None]), dim=1)
  209. def clip(
  210. self, box_size: Tuple[int, int], clip_angle_threshold: float = 1.0
  211. ) -> None:
  212. """
  213. Clip (in place) the boxes by limiting x coordinates to the range [0, width]
  214. and y coordinates to the range [0, height].
  215. For RRPN:
  216. Only clip boxes that are almost horizontal with a tolerance of
  217. clip_angle_threshold to maintain backward compatibility.
  218. Rotated boxes beyond this threshold are not clipped for two reasons:
  219. 1. There are potentially multiple ways to clip a rotated box to make it
  220. fit within the image.
  221. 2. It's tricky to make the entire rectangular box fit within the image
  222. and still be able to not leave out pixels of interest.
  223. Therefore we rely on ops like RoIAlignRotated to safely handle this.
  224. Args:
  225. box_size (height, width): The clipping box's size.
  226. clip_angle_threshold:
  227. Iff. abs(normalized(angle)) <= clip_angle_threshold (in degrees),
  228. we do the clipping as horizontal boxes.
  229. """
  230. h, w = box_size
  231. # normalize angles to be within (-180, 180] degrees
  232. self.normalize_angles()
  233. idx = torch.where(torch.abs(self.tensor[:, 4]) <= clip_angle_threshold)[0]
  234. # convert to (x1, y1, x2, y2)
  235. x1 = self.tensor[idx, 0] - self.tensor[idx, 2] / 2.0
  236. y1 = self.tensor[idx, 1] - self.tensor[idx, 3] / 2.0
  237. x2 = self.tensor[idx, 0] + self.tensor[idx, 2] / 2.0
  238. y2 = self.tensor[idx, 1] + self.tensor[idx, 3] / 2.0
  239. # clip
  240. x1.clamp_(min=0, max=w)
  241. y1.clamp_(min=0, max=h)
  242. x2.clamp_(min=0, max=w)
  243. y2.clamp_(min=0, max=h)
  244. # convert back to (xc, yc, w, h)
  245. self.tensor[idx, 0] = (x1 + x2) / 2.0
  246. self.tensor[idx, 1] = (y1 + y2) / 2.0
  247. # make sure widths and heights do not increase due to numerical errors
  248. self.tensor[idx, 2] = torch.min(self.tensor[idx, 2], x2 - x1)
  249. self.tensor[idx, 3] = torch.min(self.tensor[idx, 3], y2 - y1)
  250. def nonempty(self, threshold: float = 0.0) -> torch.Tensor:
  251. """
  252. Find boxes that are non-empty.
  253. A box is considered empty, if either of its side is no larger than threshold.
  254. Returns:
  255. Tensor: a binary vector which represents
  256. whether each box is empty (False) or non-empty (True).
  257. """
  258. box = self.tensor
  259. widths = box[:, 2]
  260. heights = box[:, 3]
  261. keep = (widths > threshold) & (heights > threshold)
  262. return keep
  263. def __getitem__(self, item) -> "RotatedBoxes":
  264. """
  265. Returns:
  266. RotatedBoxes: Create a new :class:`RotatedBoxes` by indexing.
  267. The following usage are allowed:
  268. 1. `new_boxes = boxes[3]`: return a `RotatedBoxes` which contains only one box.
  269. 2. `new_boxes = boxes[2:10]`: return a slice of boxes.
  270. 3. `new_boxes = boxes[vector]`, where vector is a torch.ByteTensor
  271. with `length = len(boxes)`. Nonzero elements in the vector will be selected.
  272. Note that the returned RotatedBoxes might share storage with this RotatedBoxes,
  273. subject to Pytorch's indexing semantics.
  274. """
  275. if isinstance(item, int):
  276. return RotatedBoxes(self.tensor[item].view(1, -1))
  277. b = self.tensor[item]
  278. assert b.dim() == 2, (
  279. "Indexing on RotatedBoxes with {} failed to return a matrix!".format(item)
  280. )
  281. return RotatedBoxes(b)
  282. def __len__(self) -> int:
  283. return self.tensor.shape[0]
  284. def __repr__(self) -> str:
  285. return "RotatedBoxes(" + str(self.tensor) + ")"
  286. def inside_box(
  287. self, box_size: Tuple[int, int], boundary_threshold: int = 0
  288. ) -> torch.Tensor:
  289. """
  290. Args:
  291. box_size (height, width): Size of the reference box covering
  292. [0, width] x [0, height]
  293. boundary_threshold (int): Boxes that extend beyond the reference box
  294. boundary by more than boundary_threshold are considered "outside".
  295. For RRPN, it might not be necessary to call this function since it's common
  296. for rotated box to extend to outside of the image boundaries
  297. (the clip function only clips the near-horizontal boxes)
  298. Returns:
  299. a binary vector, indicating whether each box is inside the reference box.
  300. """
  301. height, width = box_size
  302. cnt_x = self.tensor[..., 0]
  303. cnt_y = self.tensor[..., 1]
  304. half_w = self.tensor[..., 2] / 2.0
  305. half_h = self.tensor[..., 3] / 2.0
  306. a = self.tensor[..., 4]
  307. c = torch.abs(torch.cos(a * math.pi / 180.0))
  308. s = torch.abs(torch.sin(a * math.pi / 180.0))
  309. # This basically computes the horizontal bounding rectangle of the rotated box
  310. max_rect_dx = c * half_w + s * half_h
  311. max_rect_dy = c * half_h + s * half_w
  312. inds_inside = (
  313. (cnt_x - max_rect_dx >= -boundary_threshold)
  314. & (cnt_y - max_rect_dy >= -boundary_threshold)
  315. & (cnt_x + max_rect_dx < width + boundary_threshold)
  316. & (cnt_y + max_rect_dy < height + boundary_threshold)
  317. )
  318. return inds_inside
  319. def get_centers(self) -> torch.Tensor:
  320. """
  321. Returns:
  322. The box centers in a Nx2 array of (x, y).
  323. """
  324. return self.tensor[:, :2]
  325. def scale(self, scale_x: float, scale_y: float) -> None:
  326. """
  327. Scale the rotated box with horizontal and vertical scaling factors
  328. Note: when scale_factor_x != scale_factor_y,
  329. the rotated box does not preserve the rectangular shape when the angle
  330. is not a multiple of 90 degrees under resize transformation.
  331. Instead, the shape is a parallelogram (that has skew)
  332. Here we make an approximation by fitting a rotated rectangle to the parallelogram.
  333. """
  334. self.tensor[:, 0] *= scale_x
  335. self.tensor[:, 1] *= scale_y
  336. theta = self.tensor[:, 4] * math.pi / 180.0
  337. c = torch.cos(theta)
  338. s = torch.sin(theta)
  339. # In image space, y is top->down and x is left->right
  340. # Consider the local coordintate system for the rotated box,
  341. # where the box center is located at (0, 0), and the four vertices ABCD are
  342. # A(-w / 2, -h / 2), B(w / 2, -h / 2), C(w / 2, h / 2), D(-w / 2, h / 2)
  343. # the midpoint of the left edge AD of the rotated box E is:
  344. # E = (A+D)/2 = (-w / 2, 0)
  345. # the midpoint of the top edge AB of the rotated box F is:
  346. # F(0, -h / 2)
  347. # To get the old coordinates in the global system, apply the rotation transformation
  348. # (Note: the right-handed coordinate system for image space is yOx):
  349. # (old_x, old_y) = (s * y + c * x, c * y - s * x)
  350. # E(old) = (s * 0 + c * (-w/2), c * 0 - s * (-w/2)) = (-c * w / 2, s * w / 2)
  351. # F(old) = (s * (-h / 2) + c * 0, c * (-h / 2) - s * 0) = (-s * h / 2, -c * h / 2)
  352. # After applying the scaling factor (sfx, sfy):
  353. # E(new) = (-sfx * c * w / 2, sfy * s * w / 2)
  354. # F(new) = (-sfx * s * h / 2, -sfy * c * h / 2)
  355. # The new width after scaling tranformation becomes:
  356. # w(new) = |E(new) - O| * 2
  357. # = sqrt[(sfx * c * w / 2)^2 + (sfy * s * w / 2)^2] * 2
  358. # = sqrt[(sfx * c)^2 + (sfy * s)^2] * w
  359. # i.e., scale_factor_w = sqrt[(sfx * c)^2 + (sfy * s)^2]
  360. #
  361. # For example,
  362. # when angle = 0 or 180, |c| = 1, s = 0, scale_factor_w == scale_factor_x;
  363. # when |angle| = 90, c = 0, |s| = 1, scale_factor_w == scale_factor_y
  364. self.tensor[:, 2] *= torch.sqrt((scale_x * c) ** 2 + (scale_y * s) ** 2)
  365. # h(new) = |F(new) - O| * 2
  366. # = sqrt[(sfx * s * h / 2)^2 + (sfy * c * h / 2)^2] * 2
  367. # = sqrt[(sfx * s)^2 + (sfy * c)^2] * h
  368. # i.e., scale_factor_h = sqrt[(sfx * s)^2 + (sfy * c)^2]
  369. #
  370. # For example,
  371. # when angle = 0 or 180, |c| = 1, s = 0, scale_factor_h == scale_factor_y;
  372. # when |angle| = 90, c = 0, |s| = 1, scale_factor_h == scale_factor_x
  373. self.tensor[:, 3] *= torch.sqrt((scale_x * s) ** 2 + (scale_y * c) ** 2)
  374. # The angle is the rotation angle from y-axis in image space to the height
  375. # vector (top->down in the box's local coordinate system) of the box in CCW.
  376. #
  377. # angle(new) = angle_yOx(O - F(new))
  378. # = angle_yOx( (sfx * s * h / 2, sfy * c * h / 2) )
  379. # = atan2(sfx * s * h / 2, sfy * c * h / 2)
  380. # = atan2(sfx * s, sfy * c)
  381. #
  382. # For example,
  383. # when sfx == sfy, angle(new) == atan2(s, c) == angle(old)
  384. self.tensor[:, 4] = torch.atan2(scale_x * s, scale_y * c) * 180 / math.pi
  385. @classmethod
  386. def cat(cls, boxes_list: List["RotatedBoxes"]) -> "RotatedBoxes":
  387. """
  388. Concatenates a list of RotatedBoxes into a single RotatedBoxes
  389. Arguments:
  390. boxes_list (list[RotatedBoxes])
  391. Returns:
  392. RotatedBoxes: the concatenated RotatedBoxes
  393. """
  394. assert isinstance(boxes_list, (list, tuple))
  395. if len(boxes_list) == 0:
  396. return cls(torch.empty(0))
  397. assert all([isinstance(box, RotatedBoxes) for box in boxes_list])
  398. # use torch.cat (v.s. layers.cat) so the returned boxes never share storage with input
  399. cat_boxes = cls(torch.cat([b.tensor for b in boxes_list], dim=0))
  400. return cat_boxes
  401. @property
  402. def device(self) -> torch.device:
  403. return self.tensor.device
  404. @torch.jit.unused
  405. def __iter__(self):
  406. """
  407. Yield a box as a Tensor of shape (5,) at a time.
  408. """
  409. yield from self.tensor
  410. def pairwise_iou(boxes1: RotatedBoxes, boxes2: RotatedBoxes) -> None:
  411. """
  412. Given two lists of rotated boxes of size N and M,
  413. compute the IoU (intersection over union)
  414. between **all** N x M pairs of boxes.
  415. The box order must be (x_center, y_center, width, height, angle).
  416. Args:
  417. boxes1, boxes2 (RotatedBoxes):
  418. two `RotatedBoxes`. Contains N & M rotated boxes, respectively.
  419. Returns:
  420. Tensor: IoU, sized [N,M].
  421. """
  422. return pairwise_iou_rotated(boxes1.tensor, boxes2.tensor)