transforms.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. from typing import List, Optional, Sequence, Tuple, Union
  3. import numpy as np
  4. import torch
  5. from torch import Tensor
  6. from mmdet.structures.bbox import BaseBoxes
  7. def find_inside_bboxes(bboxes: Tensor, img_h: int, img_w: int) -> Tensor:
  8. """Find bboxes as long as a part of bboxes is inside the image.
  9. Args:
  10. bboxes (Tensor): Shape (N, 4).
  11. img_h (int): Image height.
  12. img_w (int): Image width.
  13. Returns:
  14. Tensor: Index of the remaining bboxes.
  15. """
  16. inside_inds = (bboxes[:, 0] < img_w) & (bboxes[:, 2] > 0) \
  17. & (bboxes[:, 1] < img_h) & (bboxes[:, 3] > 0)
  18. return inside_inds
  19. def bbox_flip(bboxes: Tensor,
  20. img_shape: Tuple[int],
  21. direction: str = 'horizontal') -> Tensor:
  22. """Flip bboxes horizontally or vertically.
  23. Args:
  24. bboxes (Tensor): Shape (..., 4*k)
  25. img_shape (Tuple[int]): Image shape.
  26. direction (str): Flip direction, options are "horizontal", "vertical",
  27. "diagonal". Default: "horizontal"
  28. Returns:
  29. Tensor: Flipped bboxes.
  30. """
  31. assert bboxes.shape[-1] % 4 == 0
  32. assert direction in ['horizontal', 'vertical', 'diagonal']
  33. flipped = bboxes.clone()
  34. if direction == 'horizontal':
  35. flipped[..., 0::4] = img_shape[1] - bboxes[..., 2::4]
  36. flipped[..., 2::4] = img_shape[1] - bboxes[..., 0::4]
  37. elif direction == 'vertical':
  38. flipped[..., 1::4] = img_shape[0] - bboxes[..., 3::4]
  39. flipped[..., 3::4] = img_shape[0] - bboxes[..., 1::4]
  40. else:
  41. flipped[..., 0::4] = img_shape[1] - bboxes[..., 2::4]
  42. flipped[..., 1::4] = img_shape[0] - bboxes[..., 3::4]
  43. flipped[..., 2::4] = img_shape[1] - bboxes[..., 0::4]
  44. flipped[..., 3::4] = img_shape[0] - bboxes[..., 1::4]
  45. return flipped
  46. def bbox_mapping(bboxes: Tensor,
  47. img_shape: Tuple[int],
  48. scale_factor: Union[float, Tuple[float]],
  49. flip: bool,
  50. flip_direction: str = 'horizontal') -> Tensor:
  51. """Map bboxes from the original image scale to testing scale."""
  52. new_bboxes = bboxes * bboxes.new_tensor(scale_factor)
  53. if flip:
  54. new_bboxes = bbox_flip(new_bboxes, img_shape, flip_direction)
  55. return new_bboxes
  56. def bbox_mapping_back(bboxes: Tensor,
  57. img_shape: Tuple[int],
  58. scale_factor: Union[float, Tuple[float]],
  59. flip: bool,
  60. flip_direction: str = 'horizontal') -> Tensor:
  61. """Map bboxes from testing scale to original image scale."""
  62. new_bboxes = bbox_flip(bboxes, img_shape,
  63. flip_direction) if flip else bboxes
  64. new_bboxes = new_bboxes.view(-1, 4) / new_bboxes.new_tensor(scale_factor)
  65. return new_bboxes.view(bboxes.shape)
  66. def bbox2roi(bbox_list: List[Union[Tensor, BaseBoxes]]) -> Tensor:
  67. """Convert a list of bboxes to roi format.
  68. Args:
  69. bbox_list (List[Union[Tensor, :obj:`BaseBoxes`]): a list of bboxes
  70. corresponding to a batch of images.
  71. Returns:
  72. Tensor: shape (n, box_dim + 1), where ``box_dim`` depends on the
  73. different box types. For example, If the box type in ``bbox_list``
  74. is HorizontalBoxes, the output shape is (n, 5). Each row of data
  75. indicates [batch_ind, x1, y1, x2, y2].
  76. """
  77. rois_list = []
  78. for img_id, bboxes in enumerate(bbox_list):
  79. bboxes = get_box_tensor(bboxes)
  80. img_inds = bboxes.new_full((bboxes.size(0), 1), img_id)
  81. rois = torch.cat([img_inds, bboxes], dim=-1)
  82. rois_list.append(rois)
  83. rois = torch.cat(rois_list, 0)
  84. return rois
  85. def roi2bbox(rois: Tensor) -> List[Tensor]:
  86. """Convert rois to bounding box format.
  87. Args:
  88. rois (Tensor): RoIs with the shape (n, 5) where the first
  89. column indicates batch id of each RoI.
  90. Returns:
  91. List[Tensor]: Converted boxes of corresponding rois.
  92. """
  93. bbox_list = []
  94. img_ids = torch.unique(rois[:, 0].cpu(), sorted=True)
  95. for img_id in img_ids:
  96. inds = (rois[:, 0] == img_id.item())
  97. bbox = rois[inds, 1:]
  98. bbox_list.append(bbox)
  99. return bbox_list
  100. # TODO remove later
  101. def bbox2result(bboxes: Union[Tensor, np.ndarray], labels: Union[Tensor,
  102. np.ndarray],
  103. num_classes: int) -> List[np.ndarray]:
  104. """Convert detection results to a list of numpy arrays.
  105. Args:
  106. bboxes (Tensor | np.ndarray): shape (n, 5)
  107. labels (Tensor | np.ndarray): shape (n, )
  108. num_classes (int): class number, including background class
  109. Returns:
  110. List(np.ndarray]): bbox results of each class
  111. """
  112. if bboxes.shape[0] == 0:
  113. return [np.zeros((0, 5), dtype=np.float32) for i in range(num_classes)]
  114. else:
  115. if isinstance(bboxes, torch.Tensor):
  116. bboxes = bboxes.detach().cpu().numpy()
  117. labels = labels.detach().cpu().numpy()
  118. return [bboxes[labels == i, :] for i in range(num_classes)]
  119. def distance2bbox(
  120. points: Tensor,
  121. distance: Tensor,
  122. max_shape: Optional[Union[Sequence[int], Tensor,
  123. Sequence[Sequence[int]]]] = None
  124. ) -> Tensor:
  125. """Decode distance prediction to bounding box.
  126. Args:
  127. points (Tensor): Shape (B, N, 2) or (N, 2).
  128. distance (Tensor): Distance from the given point to 4
  129. boundaries (left, top, right, bottom). Shape (B, N, 4) or (N, 4)
  130. max_shape (Union[Sequence[int], Tensor, Sequence[Sequence[int]]],
  131. optional): Maximum bounds for boxes, specifies
  132. (H, W, C) or (H, W). If priors shape is (B, N, 4), then
  133. the max_shape should be a Sequence[Sequence[int]]
  134. and the length of max_shape should also be B.
  135. Returns:
  136. Tensor: Boxes with shape (N, 4) or (B, N, 4)
  137. """
  138. x1 = points[..., 0] - distance[..., 0]
  139. y1 = points[..., 1] - distance[..., 1]
  140. x2 = points[..., 0] + distance[..., 2]
  141. y2 = points[..., 1] + distance[..., 3]
  142. bboxes = torch.stack([x1, y1, x2, y2], -1)
  143. if max_shape is not None:
  144. if bboxes.dim() == 2 and not torch.onnx.is_in_onnx_export():
  145. # speed up
  146. bboxes[:, 0::2].clamp_(min=0, max=max_shape[1])
  147. bboxes[:, 1::2].clamp_(min=0, max=max_shape[0])
  148. return bboxes
  149. # clip bboxes with dynamic `min` and `max` for onnx
  150. if torch.onnx.is_in_onnx_export():
  151. # TODO: delete
  152. from mmdet.core.export import dynamic_clip_for_onnx
  153. x1, y1, x2, y2 = dynamic_clip_for_onnx(x1, y1, x2, y2, max_shape)
  154. bboxes = torch.stack([x1, y1, x2, y2], dim=-1)
  155. return bboxes
  156. if not isinstance(max_shape, torch.Tensor):
  157. max_shape = x1.new_tensor(max_shape)
  158. max_shape = max_shape[..., :2].type_as(x1)
  159. if max_shape.ndim == 2:
  160. assert bboxes.ndim == 3
  161. assert max_shape.size(0) == bboxes.size(0)
  162. min_xy = x1.new_tensor(0)
  163. max_xy = torch.cat([max_shape, max_shape],
  164. dim=-1).flip(-1).unsqueeze(-2)
  165. bboxes = torch.where(bboxes < min_xy, min_xy, bboxes)
  166. bboxes = torch.where(bboxes > max_xy, max_xy, bboxes)
  167. return bboxes
  168. def bbox2distance(points: Tensor,
  169. bbox: Tensor,
  170. max_dis: Optional[float] = None,
  171. eps: float = 0.1) -> Tensor:
  172. """Decode bounding box based on distances.
  173. Args:
  174. points (Tensor): Shape (n, 2) or (b, n, 2), [x, y].
  175. bbox (Tensor): Shape (n, 4) or (b, n, 4), "xyxy" format
  176. max_dis (float, optional): Upper bound of the distance.
  177. eps (float): a small value to ensure target < max_dis, instead <=
  178. Returns:
  179. Tensor: Decoded distances.
  180. """
  181. left = points[..., 0] - bbox[..., 0]
  182. top = points[..., 1] - bbox[..., 1]
  183. right = bbox[..., 2] - points[..., 0]
  184. bottom = bbox[..., 3] - points[..., 1]
  185. if max_dis is not None:
  186. left = left.clamp(min=0, max=max_dis - eps)
  187. top = top.clamp(min=0, max=max_dis - eps)
  188. right = right.clamp(min=0, max=max_dis - eps)
  189. bottom = bottom.clamp(min=0, max=max_dis - eps)
  190. return torch.stack([left, top, right, bottom], -1)
  191. def bbox_rescale(bboxes: Tensor, scale_factor: float = 1.0) -> Tensor:
  192. """Rescale bounding box w.r.t. scale_factor.
  193. Args:
  194. bboxes (Tensor): Shape (n, 4) for bboxes or (n, 5) for rois
  195. scale_factor (float): rescale factor
  196. Returns:
  197. Tensor: Rescaled bboxes.
  198. """
  199. if bboxes.size(1) == 5:
  200. bboxes_ = bboxes[:, 1:]
  201. inds_ = bboxes[:, 0]
  202. else:
  203. bboxes_ = bboxes
  204. cx = (bboxes_[:, 0] + bboxes_[:, 2]) * 0.5
  205. cy = (bboxes_[:, 1] + bboxes_[:, 3]) * 0.5
  206. w = bboxes_[:, 2] - bboxes_[:, 0]
  207. h = bboxes_[:, 3] - bboxes_[:, 1]
  208. w = w * scale_factor
  209. h = h * scale_factor
  210. x1 = cx - 0.5 * w
  211. x2 = cx + 0.5 * w
  212. y1 = cy - 0.5 * h
  213. y2 = cy + 0.5 * h
  214. if bboxes.size(1) == 5:
  215. rescaled_bboxes = torch.stack([inds_, x1, y1, x2, y2], dim=-1)
  216. else:
  217. rescaled_bboxes = torch.stack([x1, y1, x2, y2], dim=-1)
  218. return rescaled_bboxes
  219. def bbox_cxcywh_to_xyxy(bbox: Tensor) -> Tensor:
  220. """Convert bbox coordinates from (cx, cy, w, h) to (x1, y1, x2, y2).
  221. Args:
  222. bbox (Tensor): Shape (n, 4) for bboxes.
  223. Returns:
  224. Tensor: Converted bboxes.
  225. """
  226. cx, cy, w, h = bbox.split((1, 1, 1, 1), dim=-1)
  227. bbox_new = [(cx - 0.5 * w), (cy - 0.5 * h), (cx + 0.5 * w), (cy + 0.5 * h)]
  228. return torch.cat(bbox_new, dim=-1)
  229. def bbox_xyxy_to_cxcywh(bbox: Tensor) -> Tensor:
  230. """Convert bbox coordinates from (x1, y1, x2, y2) to (cx, cy, w, h).
  231. Args:
  232. bbox (Tensor): Shape (n, 4) for bboxes.
  233. Returns:
  234. Tensor: Converted bboxes.
  235. """
  236. x1, y1, x2, y2 = bbox.split((1, 1, 1, 1), dim=-1)
  237. bbox_new = [(x1 + x2) / 2, (y1 + y2) / 2, (x2 - x1), (y2 - y1)]
  238. return torch.cat(bbox_new, dim=-1)
  239. def bbox2corner(bboxes: torch.Tensor) -> torch.Tensor:
  240. """Convert bbox coordinates from (x1, y1, x2, y2) to corners ((x1, y1),
  241. (x2, y1), (x1, y2), (x2, y2)).
  242. Args:
  243. bboxes (Tensor): Shape (n, 4) for bboxes.
  244. Returns:
  245. Tensor: Shape (n*4, 2) for corners.
  246. """
  247. x1, y1, x2, y2 = torch.split(bboxes, 1, dim=1)
  248. return torch.cat([x1, y1, x2, y1, x1, y2, x2, y2], dim=1).reshape(-1, 2)
  249. def corner2bbox(corners: torch.Tensor) -> torch.Tensor:
  250. """Convert bbox coordinates from corners ((x1, y1), (x2, y1), (x1, y2),
  251. (x2, y2)) to (x1, y1, x2, y2).
  252. Args:
  253. corners (Tensor): Shape (n*4, 2) for corners.
  254. Returns:
  255. Tensor: Shape (n, 4) for bboxes.
  256. """
  257. corners = corners.reshape(-1, 4, 2)
  258. min_xy = corners.min(dim=1)[0]
  259. max_xy = corners.max(dim=1)[0]
  260. return torch.cat([min_xy, max_xy], dim=1)
  261. def bbox_project(
  262. bboxes: Union[torch.Tensor, np.ndarray],
  263. homography_matrix: Union[torch.Tensor, np.ndarray],
  264. img_shape: Optional[Tuple[int, int]] = None
  265. ) -> Union[torch.Tensor, np.ndarray]:
  266. """Geometric transformation for bbox.
  267. Args:
  268. bboxes (Union[torch.Tensor, np.ndarray]): Shape (n, 4) for bboxes.
  269. homography_matrix (Union[torch.Tensor, np.ndarray]):
  270. Shape (3, 3) for geometric transformation.
  271. img_shape (Tuple[int, int], optional): Image shape. Defaults to None.
  272. Returns:
  273. Union[torch.Tensor, np.ndarray]: Converted bboxes.
  274. """
  275. bboxes_type = type(bboxes)
  276. if bboxes_type is np.ndarray:
  277. bboxes = torch.from_numpy(bboxes)
  278. if isinstance(homography_matrix, np.ndarray):
  279. homography_matrix = torch.from_numpy(homography_matrix)
  280. corners = bbox2corner(bboxes)
  281. corners = torch.cat(
  282. [corners, corners.new_ones(corners.shape[0], 1)], dim=1)
  283. corners = torch.matmul(homography_matrix, corners.t()).t()
  284. # Convert to homogeneous coordinates by normalization
  285. corners = corners[:, :2] / corners[:, 2:3]
  286. bboxes = corner2bbox(corners)
  287. if img_shape is not None:
  288. bboxes[:, 0::2] = bboxes[:, 0::2].clamp(0, img_shape[1])
  289. bboxes[:, 1::2] = bboxes[:, 1::2].clamp(0, img_shape[0])
  290. if bboxes_type is np.ndarray:
  291. bboxes = bboxes.numpy()
  292. return bboxes
  293. def cat_boxes(data_list: List[Union[Tensor, BaseBoxes]],
  294. dim: int = 0) -> Union[Tensor, BaseBoxes]:
  295. """Concatenate boxes with type of tensor or box type.
  296. Args:
  297. data_list (List[Union[Tensor, :obj:`BaseBoxes`]]): A list of tensors
  298. or box types need to be concatenated.
  299. dim (int): The dimension over which the box are concatenated.
  300. Defaults to 0.
  301. Returns:
  302. Union[Tensor, :obj`BaseBoxes`]: Concatenated results.
  303. """
  304. if data_list and isinstance(data_list[0], BaseBoxes):
  305. return data_list[0].cat(data_list, dim=dim)
  306. else:
  307. return torch.cat(data_list, dim=dim)
  308. def stack_boxes(data_list: List[Union[Tensor, BaseBoxes]],
  309. dim: int = 0) -> Union[Tensor, BaseBoxes]:
  310. """Stack boxes with type of tensor or box type.
  311. Args:
  312. data_list (List[Union[Tensor, :obj:`BaseBoxes`]]): A list of tensors
  313. or box types need to be stacked.
  314. dim (int): The dimension over which the box are stacked.
  315. Defaults to 0.
  316. Returns:
  317. Union[Tensor, :obj`BaseBoxes`]: Stacked results.
  318. """
  319. if data_list and isinstance(data_list[0], BaseBoxes):
  320. return data_list[0].stack(data_list, dim=dim)
  321. else:
  322. return torch.stack(data_list, dim=dim)
  323. def scale_boxes(boxes: Union[Tensor, BaseBoxes],
  324. scale_factor: Tuple[float, float]) -> Union[Tensor, BaseBoxes]:
  325. """Scale boxes with type of tensor or box type.
  326. Args:
  327. boxes (Tensor or :obj:`BaseBoxes`): boxes need to be scaled. Its type
  328. can be a tensor or a box type.
  329. scale_factor (Tuple[float, float]): factors for scaling boxes.
  330. The length should be 2.
  331. Returns:
  332. Union[Tensor, :obj:`BaseBoxes`]: Scaled boxes.
  333. """
  334. if isinstance(boxes, BaseBoxes):
  335. boxes.rescale_(scale_factor)
  336. return boxes
  337. else:
  338. # Tensor boxes will be treated as horizontal boxes
  339. repeat_num = int(boxes.size(-1) / 2)
  340. scale_factor = boxes.new_tensor(scale_factor).repeat((1, repeat_num))
  341. return boxes * scale_factor
  342. def get_box_wh(boxes: Union[Tensor, BaseBoxes]) -> Tuple[Tensor, Tensor]:
  343. """Get the width and height of boxes with type of tensor or box type.
  344. Args:
  345. boxes (Tensor or :obj:`BaseBoxes`): boxes with type of tensor
  346. or box type.
  347. Returns:
  348. Tuple[Tensor, Tensor]: the width and height of boxes.
  349. """
  350. if isinstance(boxes, BaseBoxes):
  351. w = boxes.widths
  352. h = boxes.heights
  353. else:
  354. # Tensor boxes will be treated as horizontal boxes by defaults
  355. w = boxes[:, 2] - boxes[:, 0]
  356. h = boxes[:, 3] - boxes[:, 1]
  357. return w, h
  358. def get_box_tensor(boxes: Union[Tensor, BaseBoxes]) -> Tensor:
  359. """Get tensor data from box type boxes.
  360. Args:
  361. boxes (Tensor or BaseBoxes): boxes with type of tensor or box type.
  362. If its type is a tensor, the boxes will be directly returned.
  363. If its type is a box type, the `boxes.tensor` will be returned.
  364. Returns:
  365. Tensor: boxes tensor.
  366. """
  367. if isinstance(boxes, BaseBoxes):
  368. boxes = boxes.tensor
  369. return boxes
  370. def empty_box_as(boxes: Union[Tensor, BaseBoxes]) -> Union[Tensor, BaseBoxes]:
  371. """Generate empty box according to input ``boxes` type and device.
  372. Args:
  373. boxes (Tensor or :obj:`BaseBoxes`): boxes with type of tensor
  374. or box type.
  375. Returns:
  376. Union[Tensor, BaseBoxes]: Generated empty box.
  377. """
  378. if isinstance(boxes, BaseBoxes):
  379. return boxes.empty_boxes()
  380. else:
  381. # Tensor boxes will be treated as horizontal boxes by defaults
  382. return boxes.new_zeros(0, 4)
  383. def bbox_xyxy_to_cxcyah(bboxes: torch.Tensor) -> torch.Tensor:
  384. """Convert bbox coordinates from (x1, y1, x2, y2) to (cx, cy, ratio, h).
  385. Args:
  386. bbox (Tensor): Shape (n, 4) for bboxes.
  387. Returns:
  388. Tensor: Converted bboxes.
  389. """
  390. cx = (bboxes[:, 2] + bboxes[:, 0]) / 2
  391. cy = (bboxes[:, 3] + bboxes[:, 1]) / 2
  392. w = bboxes[:, 2] - bboxes[:, 0]
  393. h = bboxes[:, 3] - bboxes[:, 1]
  394. xyah = torch.stack([cx, cy, w / h, h], -1)
  395. return xyah
  396. def bbox_cxcyah_to_xyxy(bboxes: torch.Tensor) -> torch.Tensor:
  397. """Convert bbox coordinates from (cx, cy, ratio, h) to (x1, y1, x2, y2).
  398. Args:
  399. bbox (Tensor): Shape (n, 4) for bboxes.
  400. Returns:
  401. Tensor: Converted bboxes.
  402. """
  403. cx, cy, ratio, h = bboxes.split((1, 1, 1, 1), dim=-1)
  404. w = ratio * h
  405. x1y1x2y2 = [cx - w / 2.0, cy - h / 2.0, cx + w / 2.0, cy + h / 2.0]
  406. return torch.cat(x1y1x2y2, dim=-1)