bbox_utils.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import math
  15. import paddle
  16. import numpy as np
  17. def bbox2delta(src_boxes, tgt_boxes, weights):
  18. src_w = src_boxes[:, 2] - src_boxes[:, 0]
  19. src_h = src_boxes[:, 3] - src_boxes[:, 1]
  20. src_ctr_x = src_boxes[:, 0] + 0.5 * src_w
  21. src_ctr_y = src_boxes[:, 1] + 0.5 * src_h
  22. tgt_w = tgt_boxes[:, 2] - tgt_boxes[:, 0]
  23. tgt_h = tgt_boxes[:, 3] - tgt_boxes[:, 1]
  24. tgt_ctr_x = tgt_boxes[:, 0] + 0.5 * tgt_w
  25. tgt_ctr_y = tgt_boxes[:, 1] + 0.5 * tgt_h
  26. wx, wy, ww, wh = weights
  27. dx = wx * (tgt_ctr_x - src_ctr_x) / src_w
  28. dy = wy * (tgt_ctr_y - src_ctr_y) / src_h
  29. dw = ww * paddle.log(tgt_w / src_w)
  30. dh = wh * paddle.log(tgt_h / src_h)
  31. deltas = paddle.stack((dx, dy, dw, dh), axis=1)
  32. return deltas
  33. def delta2bbox(deltas, boxes, weights):
  34. clip_scale = math.log(1000.0 / 16)
  35. widths = boxes[:, 2] - boxes[:, 0]
  36. heights = boxes[:, 3] - boxes[:, 1]
  37. ctr_x = boxes[:, 0] + 0.5 * widths
  38. ctr_y = boxes[:, 1] + 0.5 * heights
  39. wx, wy, ww, wh = weights
  40. dx = deltas[:, 0::4] / wx
  41. dy = deltas[:, 1::4] / wy
  42. dw = deltas[:, 2::4] / ww
  43. dh = deltas[:, 3::4] / wh
  44. # Prevent sending too large values into paddle.exp()
  45. dw = paddle.clip(dw, max=clip_scale)
  46. dh = paddle.clip(dh, max=clip_scale)
  47. pred_ctr_x = dx * widths.unsqueeze(1) + ctr_x.unsqueeze(1)
  48. pred_ctr_y = dy * heights.unsqueeze(1) + ctr_y.unsqueeze(1)
  49. pred_w = paddle.exp(dw) * widths.unsqueeze(1)
  50. pred_h = paddle.exp(dh) * heights.unsqueeze(1)
  51. pred_boxes = []
  52. pred_boxes.append(pred_ctr_x - 0.5 * pred_w)
  53. pred_boxes.append(pred_ctr_y - 0.5 * pred_h)
  54. pred_boxes.append(pred_ctr_x + 0.5 * pred_w)
  55. pred_boxes.append(pred_ctr_y + 0.5 * pred_h)
  56. pred_boxes = paddle.stack(pred_boxes, axis=-1)
  57. return pred_boxes
  58. def expand_bbox(bboxes, scale):
  59. w_half = (bboxes[:, 2] - bboxes[:, 0]) * .5
  60. h_half = (bboxes[:, 3] - bboxes[:, 1]) * .5
  61. x_c = (bboxes[:, 2] + bboxes[:, 0]) * .5
  62. y_c = (bboxes[:, 3] + bboxes[:, 1]) * .5
  63. w_half *= scale
  64. h_half *= scale
  65. bboxes_exp = np.zeros(bboxes.shape, dtype=np.float32)
  66. bboxes_exp[:, 0] = x_c - w_half
  67. bboxes_exp[:, 2] = x_c + w_half
  68. bboxes_exp[:, 1] = y_c - h_half
  69. bboxes_exp[:, 3] = y_c + h_half
  70. return bboxes_exp
  71. def clip_bbox(boxes, im_shape):
  72. h, w = im_shape[0], im_shape[1]
  73. x1 = boxes[:, 0].clip(0, w)
  74. y1 = boxes[:, 1].clip(0, h)
  75. x2 = boxes[:, 2].clip(0, w)
  76. y2 = boxes[:, 3].clip(0, h)
  77. return paddle.stack([x1, y1, x2, y2], axis=1)
  78. def nonempty_bbox(boxes, min_size=0, return_mask=False):
  79. w = boxes[:, 2] - boxes[:, 0]
  80. h = boxes[:, 3] - boxes[:, 1]
  81. mask = paddle.logical_and(w > min_size, w > min_size)
  82. if return_mask:
  83. return mask
  84. keep = paddle.nonzero(mask).flatten()
  85. return keep
  86. def bbox_area(boxes):
  87. return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
  88. def bbox_overlaps(boxes1, boxes2):
  89. """
  90. Calculate overlaps between boxes1 and boxes2
  91. Args:
  92. boxes1 (Tensor): boxes with shape [M, 4]
  93. boxes2 (Tensor): boxes with shape [N, 4]
  94. Return:
  95. overlaps (Tensor): overlaps between boxes1 and boxes2 with shape [M, N]
  96. """
  97. M = boxes1.shape[0]
  98. N = boxes2.shape[0]
  99. if M * N == 0:
  100. return paddle.zeros([M, N], dtype='float32')
  101. area1 = bbox_area(boxes1)
  102. area2 = bbox_area(boxes2)
  103. xy_max = paddle.minimum(
  104. paddle.unsqueeze(boxes1, 1)[:, :, 2:], boxes2[:, 2:])
  105. xy_min = paddle.maximum(
  106. paddle.unsqueeze(boxes1, 1)[:, :, :2], boxes2[:, :2])
  107. width_height = xy_max - xy_min
  108. width_height = width_height.clip(min=0)
  109. inter = width_height.prod(axis=2)
  110. overlaps = paddle.where(inter > 0, inter /
  111. (paddle.unsqueeze(area1, 1) + area2 - inter),
  112. paddle.zeros_like(inter))
  113. return overlaps
  114. def xywh2xyxy(box):
  115. x, y, w, h = box
  116. x1 = x - w * 0.5
  117. y1 = y - h * 0.5
  118. x2 = x + w * 0.5
  119. y2 = y + h * 0.5
  120. return [x1, y1, x2, y2]
  121. def make_grid(h, w, dtype):
  122. yv, xv = paddle.meshgrid([paddle.arange(h), paddle.arange(w)])
  123. return paddle.stack((xv, yv), 2).cast(dtype=dtype)
  124. def decode_yolo(box, anchor, downsample_ratio):
  125. """decode yolo box
  126. Args:
  127. box (list): [x, y, w, h], all have the shape [b, na, h, w, 1]
  128. anchor (list): anchor with the shape [na, 2]
  129. downsample_ratio (int): downsample ratio, default 32
  130. scale (float): scale, default 1.
  131. Return:
  132. box (list): decoded box, [x, y, w, h], all have the shape [b, na, h, w, 1]
  133. """
  134. x, y, w, h = box
  135. na, grid_h, grid_w = x.shape[1:4]
  136. grid = make_grid(grid_h, grid_w, x.dtype).reshape(
  137. (1, 1, grid_h, grid_w, 2))
  138. x1 = (x + grid[:, :, :, :, 0:1]) / grid_w
  139. y1 = (y + grid[:, :, :, :, 1:2]) / grid_h
  140. anchor = paddle.to_tensor(anchor)
  141. anchor = paddle.cast(anchor, x.dtype)
  142. anchor = anchor.reshape((1, na, 1, 1, 2))
  143. w1 = paddle.exp(w) * anchor[:, :, :, :, 0:1] / (downsample_ratio * grid_w)
  144. h1 = paddle.exp(h) * anchor[:, :, :, :, 1:2] / (downsample_ratio * grid_h)
  145. return [x1, y1, w1, h1]
  146. def iou_similarity(box1, box2, eps=1e-9):
  147. """Calculate iou of box1 and box2
  148. Args:
  149. box1 (Tensor): box with the shape [N, M1, 4]
  150. box2 (Tensor): box with the shape [N, M2, 4]
  151. Return:
  152. iou (Tensor): iou between box1 and box2 with the shape [N, M1, M2]
  153. """
  154. box1 = box1.unsqueeze(2) # [N, M1, 4] -> [N, M1, 1, 4]
  155. box2 = box2.unsqueeze(1) # [N, M2, 4] -> [N, 1, M2, 4]
  156. px1y1, px2y2 = box1[:, :, :, 0:2], box1[:, :, :, 2:4]
  157. gx1y1, gx2y2 = box2[:, :, :, 0:2], box2[:, :, :, 2:4]
  158. x1y1 = paddle.maximum(px1y1, gx1y1)
  159. x2y2 = paddle.minimum(px2y2, gx2y2)
  160. overlap = (x2y2 - x1y1).clip(0).prod(-1)
  161. area1 = (px2y2 - px1y1).clip(0).prod(-1)
  162. area2 = (gx2y2 - gx1y1).clip(0).prod(-1)
  163. union = area1 + area2 - overlap + eps
  164. return overlap / union
  165. def bbox_iou(box1, box2, giou=False, diou=False, ciou=False, eps=1e-9):
  166. """calculate the iou of box1 and box2
  167. Args:
  168. box1 (list): [x, y, w, h], all have the shape [b, na, h, w, 1]
  169. box2 (list): [x, y, w, h], all have the shape [b, na, h, w, 1]
  170. giou (bool): whether use giou or not, default False
  171. diou (bool): whether use diou or not, default False
  172. ciou (bool): whether use ciou or not, default False
  173. eps (float): epsilon to avoid divide by zero
  174. Return:
  175. iou (Tensor): iou of box1 and box1, with the shape [b, na, h, w, 1]
  176. """
  177. px1, py1, px2, py2 = box1
  178. gx1, gy1, gx2, gy2 = box2
  179. x1 = paddle.maximum(px1, gx1)
  180. y1 = paddle.maximum(py1, gy1)
  181. x2 = paddle.minimum(px2, gx2)
  182. y2 = paddle.minimum(py2, gy2)
  183. overlap = ((x2 - x1).clip(0)) * ((y2 - y1).clip(0))
  184. area1 = (px2 - px1) * (py2 - py1)
  185. area1 = area1.clip(0)
  186. area2 = (gx2 - gx1) * (gy2 - gy1)
  187. area2 = area2.clip(0)
  188. union = area1 + area2 - overlap + eps
  189. iou = overlap / union
  190. if giou or ciou or diou:
  191. # convex w, h
  192. cw = paddle.maximum(px2, gx2) - paddle.minimum(px1, gx1)
  193. ch = paddle.maximum(py2, gy2) - paddle.minimum(py1, gy1)
  194. if giou:
  195. c_area = cw * ch + eps
  196. return iou - (c_area - union) / c_area
  197. else:
  198. # convex diagonal squared
  199. c2 = cw**2 + ch**2 + eps
  200. # center distance
  201. rho2 = (
  202. (px1 + px2 - gx1 - gx2)**2 + (py1 + py2 - gy1 - gy2)**2) / 4
  203. if diou:
  204. return iou - rho2 / c2
  205. else:
  206. w1, h1 = px2 - px1, py2 - py1 + eps
  207. w2, h2 = gx2 - gx1, gy2 - gy1 + eps
  208. delta = paddle.atan(w1 / h1) - paddle.atan(w2 / h2)
  209. v = (4 / math.pi**2) * paddle.pow(delta, 2)
  210. alpha = v / (1 + eps - iou + v)
  211. alpha.stop_gradient = True
  212. return iou - (rho2 / c2 + v * alpha)
  213. else:
  214. return iou
  215. def rect2rbox(bboxes):
  216. """
  217. :param bboxes: shape (n, 4) (xmin, ymin, xmax, ymax)
  218. :return: dbboxes: shape (n, 5) (x_ctr, y_ctr, w, h, angle)
  219. """
  220. bboxes = bboxes.reshape(-1, 4)
  221. num_boxes = bboxes.shape[0]
  222. x_ctr = (bboxes[:, 2] + bboxes[:, 0]) / 2.0
  223. y_ctr = (bboxes[:, 3] + bboxes[:, 1]) / 2.0
  224. edges1 = np.abs(bboxes[:, 2] - bboxes[:, 0])
  225. edges2 = np.abs(bboxes[:, 3] - bboxes[:, 1])
  226. angles = np.zeros([num_boxes], dtype=bboxes.dtype)
  227. inds = edges1 < edges2
  228. rboxes = np.stack((x_ctr, y_ctr, edges1, edges2, angles), axis=1)
  229. rboxes[inds, 2] = edges2[inds]
  230. rboxes[inds, 3] = edges1[inds]
  231. rboxes[inds, 4] = np.pi / 2.0
  232. return rboxes
  233. def delta2rbox(rrois,
  234. deltas,
  235. means=[0, 0, 0, 0, 0],
  236. stds=[1, 1, 1, 1, 1],
  237. wh_ratio_clip=1e-6):
  238. """
  239. :param rrois: (cx, cy, w, h, theta)
  240. :param deltas: (dx, dy, dw, dh, dtheta)
  241. :param means:
  242. :param stds:
  243. :param wh_ratio_clip:
  244. :return:
  245. """
  246. means = paddle.to_tensor(means)
  247. stds = paddle.to_tensor(stds)
  248. deltas = paddle.reshape(deltas, [-1, deltas.shape[-1]])
  249. denorm_deltas = deltas * stds + means
  250. dx = denorm_deltas[:, 0]
  251. dy = denorm_deltas[:, 1]
  252. dw = denorm_deltas[:, 2]
  253. dh = denorm_deltas[:, 3]
  254. dangle = denorm_deltas[:, 4]
  255. max_ratio = np.abs(np.log(wh_ratio_clip))
  256. dw = paddle.clip(dw, min=-max_ratio, max=max_ratio)
  257. dh = paddle.clip(dh, min=-max_ratio, max=max_ratio)
  258. rroi_x = rrois[:, 0]
  259. rroi_y = rrois[:, 1]
  260. rroi_w = rrois[:, 2]
  261. rroi_h = rrois[:, 3]
  262. rroi_angle = rrois[:, 4]
  263. gx = dx * rroi_w * paddle.cos(rroi_angle) - dy * rroi_h * paddle.sin(
  264. rroi_angle) + rroi_x
  265. gy = dx * rroi_w * paddle.sin(rroi_angle) + dy * rroi_h * paddle.cos(
  266. rroi_angle) + rroi_y
  267. gw = rroi_w * dw.exp()
  268. gh = rroi_h * dh.exp()
  269. ga = np.pi * dangle + rroi_angle
  270. ga = (ga + np.pi / 4) % np.pi - np.pi / 4
  271. ga = paddle.to_tensor(ga)
  272. gw = paddle.to_tensor(gw, dtype='float32')
  273. gh = paddle.to_tensor(gh, dtype='float32')
  274. bboxes = paddle.stack([gx, gy, gw, gh, ga], axis=-1)
  275. return bboxes
  276. def rbox2delta(proposals, gt, means=[0, 0, 0, 0, 0], stds=[1, 1, 1, 1, 1]):
  277. """
  278. Args:
  279. proposals:
  280. gt:
  281. means: 1x5
  282. stds: 1x5
  283. Returns:
  284. """
  285. proposals = proposals.astype(np.float64)
  286. PI = np.pi
  287. gt_widths = gt[..., 2]
  288. gt_heights = gt[..., 3]
  289. gt_angle = gt[..., 4]
  290. proposals_widths = proposals[..., 2]
  291. proposals_heights = proposals[..., 3]
  292. proposals_angle = proposals[..., 4]
  293. coord = gt[..., 0:2] - proposals[..., 0:2]
  294. dx = (np.cos(proposals[..., 4]) * coord[..., 0] + np.sin(proposals[..., 4])
  295. * coord[..., 1]) / proposals_widths
  296. dy = (-np.sin(proposals[..., 4]) * coord[..., 0] +
  297. np.cos(proposals[..., 4]) * coord[..., 1]) / proposals_heights
  298. dw = np.log(gt_widths / proposals_widths)
  299. dh = np.log(gt_heights / proposals_heights)
  300. da = (gt_angle - proposals_angle)
  301. da = (da + PI / 4) % PI - PI / 4
  302. da /= PI
  303. deltas = np.stack([dx, dy, dw, dh, da], axis=-1)
  304. means = np.array(means, dtype=deltas.dtype)
  305. stds = np.array(stds, dtype=deltas.dtype)
  306. deltas = (deltas - means) / stds
  307. deltas = deltas.astype(np.float32)
  308. return deltas
  309. def bbox_decode(bbox_preds,
  310. anchors,
  311. means=[0, 0, 0, 0, 0],
  312. stds=[1, 1, 1, 1, 1]):
  313. """decode bbox from deltas
  314. Args:
  315. bbox_preds: [N,H,W,5]
  316. anchors: [H*W,5]
  317. return:
  318. bboxes: [N,H,W,5]
  319. """
  320. means = paddle.to_tensor(means)
  321. stds = paddle.to_tensor(stds)
  322. num_imgs, H, W, _ = bbox_preds.shape
  323. bboxes_list = []
  324. for img_id in range(num_imgs):
  325. bbox_pred = bbox_preds[img_id]
  326. # bbox_pred.shape=[5,H,W]
  327. bbox_delta = bbox_pred
  328. anchors = paddle.to_tensor(anchors)
  329. bboxes = delta2rbox(
  330. anchors, bbox_delta, means, stds, wh_ratio_clip=1e-6)
  331. bboxes = paddle.reshape(bboxes, [H, W, 5])
  332. bboxes_list.append(bboxes)
  333. return paddle.stack(bboxes_list, axis=0)
  334. def poly2rbox(polys):
  335. """
  336. poly:[x0,y0,x1,y1,x2,y2,x3,y3]
  337. to
  338. rotated_boxes:[x_ctr,y_ctr,w,h,angle]
  339. """
  340. rotated_boxes = []
  341. for poly in polys:
  342. poly = np.array(poly[:8], dtype=np.float32)
  343. pt1 = (poly[0], poly[1])
  344. pt2 = (poly[2], poly[3])
  345. pt3 = (poly[4], poly[5])
  346. pt4 = (poly[6], poly[7])
  347. edge1 = np.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[
  348. 1]) * (pt1[1] - pt2[1]))
  349. edge2 = np.sqrt((pt2[0] - pt3[0]) * (pt2[0] - pt3[0]) + (pt2[1] - pt3[
  350. 1]) * (pt2[1] - pt3[1]))
  351. width = max(edge1, edge2)
  352. height = min(edge1, edge2)
  353. rbox_angle = 0
  354. if edge1 > edge2:
  355. rbox_angle = np.arctan2(
  356. np.float(pt2[1] - pt1[1]), np.float(pt2[0] - pt1[0]))
  357. elif edge2 >= edge1:
  358. rbox_angle = np.arctan2(
  359. np.float(pt4[1] - pt1[1]), np.float(pt4[0] - pt1[0]))
  360. def norm_angle(angle, range=[-np.pi / 4, np.pi]):
  361. return (angle - range[0]) % range[1] + range[0]
  362. rbox_angle = norm_angle(rbox_angle)
  363. x_ctr = np.float(pt1[0] + pt3[0]) / 2
  364. y_ctr = np.float(pt1[1] + pt3[1]) / 2
  365. rotated_box = np.array([x_ctr, y_ctr, width, height, rbox_angle])
  366. rotated_boxes.append(rotated_box)
  367. ret_rotated_boxes = np.array(rotated_boxes)
  368. assert ret_rotated_boxes.shape[1] == 5
  369. return ret_rotated_boxes
  370. def cal_line_length(point1, point2):
  371. import math
  372. return math.sqrt(
  373. math.pow(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1],
  374. 2))
  375. def get_best_begin_point_single(coordinate):
  376. x1, y1, x2, y2, x3, y3, x4, y4 = coordinate
  377. xmin = min(x1, x2, x3, x4)
  378. ymin = min(y1, y2, y3, y4)
  379. xmax = max(x1, x2, x3, x4)
  380. ymax = max(y1, y2, y3, y4)
  381. combinate = [[[x1, y1], [x2, y2], [x3, y3], [x4, y4]],
  382. [[x4, y4], [x1, y1], [x2, y2], [x3, y3]],
  383. [[x3, y3], [x4, y4], [x1, y1], [x2, y2]],
  384. [[x2, y2], [x3, y3], [x4, y4], [x1, y1]]]
  385. dst_coordinate = [[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]]
  386. force = 100000000.0
  387. force_flag = 0
  388. for i in range(4):
  389. temp_force = cal_line_length(combinate[i][0], dst_coordinate[0]) \
  390. + cal_line_length(combinate[i][1], dst_coordinate[1]) \
  391. + cal_line_length(combinate[i][2], dst_coordinate[2]) \
  392. + cal_line_length(combinate[i][3], dst_coordinate[3])
  393. if temp_force < force:
  394. force = temp_force
  395. force_flag = i
  396. if force_flag != 0:
  397. pass
  398. return np.array(combinate[force_flag]).reshape(8)
  399. def rbox2poly_np(rrects):
  400. """
  401. rrect:[x_ctr,y_ctr,w,h,angle]
  402. to
  403. poly:[x0,y0,x1,y1,x2,y2,x3,y3]
  404. """
  405. polys = []
  406. for i in range(rrects.shape[0]):
  407. rrect = rrects[i]
  408. # x_ctr, y_ctr, width, height, angle = rrect[:5]
  409. x_ctr = rrect[0]
  410. y_ctr = rrect[1]
  411. width = rrect[2]
  412. height = rrect[3]
  413. angle = rrect[4]
  414. tl_x, tl_y, br_x, br_y = -width / 2, -height / 2, width / 2, height / 2
  415. rect = np.array([[tl_x, br_x, br_x, tl_x], [tl_y, tl_y, br_y, br_y]])
  416. R = np.array([[np.cos(angle), -np.sin(angle)],
  417. [np.sin(angle), np.cos(angle)]])
  418. poly = R.dot(rect)
  419. x0, x1, x2, x3 = poly[0, :4] + x_ctr
  420. y0, y1, y2, y3 = poly[1, :4] + y_ctr
  421. poly = np.array([x0, y0, x1, y1, x2, y2, x3, y3], dtype=np.float32)
  422. poly = get_best_begin_point_single(poly)
  423. polys.append(poly)
  424. polys = np.array(polys)
  425. return polys
  426. def rbox2poly(rrects):
  427. """
  428. rrect:[x_ctr,y_ctr,w,h,angle]
  429. to
  430. poly:[x0,y0,x1,y1,x2,y2,x3,y3]
  431. """
  432. N = paddle.shape(rrects)[0]
  433. x_ctr = rrects[:, 0]
  434. y_ctr = rrects[:, 1]
  435. width = rrects[:, 2]
  436. height = rrects[:, 3]
  437. angle = rrects[:, 4]
  438. tl_x, tl_y, br_x, br_y = -width * 0.5, -height * 0.5, width * 0.5, height * 0.5
  439. normal_rects = paddle.stack(
  440. [tl_x, br_x, br_x, tl_x, tl_y, tl_y, br_y, br_y], axis=0)
  441. normal_rects = paddle.reshape(normal_rects, [2, 4, N])
  442. normal_rects = paddle.transpose(normal_rects, [2, 0, 1])
  443. sin, cos = paddle.sin(angle), paddle.cos(angle)
  444. # M.shape=[N,2,2]
  445. M = paddle.stack([cos, -sin, sin, cos], axis=0)
  446. M = paddle.reshape(M, [2, 2, N])
  447. M = paddle.transpose(M, [2, 0, 1])
  448. # polys:[N,8]
  449. polys = paddle.matmul(M, normal_rects)
  450. polys = paddle.transpose(polys, [2, 1, 0])
  451. polys = paddle.reshape(polys, [-1, N])
  452. polys = paddle.transpose(polys, [1, 0])
  453. tmp = paddle.stack(
  454. [x_ctr, y_ctr, x_ctr, y_ctr, x_ctr, y_ctr, x_ctr, y_ctr], axis=1)
  455. polys = polys + tmp
  456. return polys
  457. def bbox_iou_np_expand(box1, box2, x1y1x2y2=True, eps=1e-16):
  458. """
  459. Calculate the iou of box1 and box2 with numpy.
  460. Args:
  461. box1 (ndarray): [N, 4]
  462. box2 (ndarray): [M, 4], usually N != M
  463. x1y1x2y2 (bool): whether in x1y1x2y2 stype, default True
  464. eps (float): epsilon to avoid divide by zero
  465. Return:
  466. iou (ndarray): iou of box1 and box2, [N, M]
  467. """
  468. N, M = len(box1), len(box2) # usually N != M
  469. if x1y1x2y2:
  470. b1_x1, b1_y1 = box1[:, 0], box1[:, 1]
  471. b1_x2, b1_y2 = box1[:, 2], box1[:, 3]
  472. b2_x1, b2_y1 = box2[:, 0], box2[:, 1]
  473. b2_x2, b2_y2 = box2[:, 2], box2[:, 3]
  474. else:
  475. # cxcywh style
  476. # Transform from center and width to exact coordinates
  477. b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2
  478. b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2
  479. b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2
  480. b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2
  481. # get the coordinates of the intersection rectangle
  482. inter_rect_x1 = np.zeros((N, M), dtype=np.float32)
  483. inter_rect_y1 = np.zeros((N, M), dtype=np.float32)
  484. inter_rect_x2 = np.zeros((N, M), dtype=np.float32)
  485. inter_rect_y2 = np.zeros((N, M), dtype=np.float32)
  486. for i in range(len(box2)):
  487. inter_rect_x1[:, i] = np.maximum(b1_x1, b2_x1[i])
  488. inter_rect_y1[:, i] = np.maximum(b1_y1, b2_y1[i])
  489. inter_rect_x2[:, i] = np.minimum(b1_x2, b2_x2[i])
  490. inter_rect_y2[:, i] = np.minimum(b1_y2, b2_y2[i])
  491. # Intersection area
  492. inter_area = np.maximum(inter_rect_x2 - inter_rect_x1, 0) * np.maximum(
  493. inter_rect_y2 - inter_rect_y1, 0)
  494. # Union Area
  495. b1_area = np.repeat(
  496. ((b1_x2 - b1_x1) * (b1_y2 - b1_y1)).reshape(-1, 1), M, axis=-1)
  497. b2_area = np.repeat(
  498. ((b2_x2 - b2_x1) * (b2_y2 - b2_y1)).reshape(1, -1), N, axis=0)
  499. ious = inter_area / (b1_area + b2_area - inter_area + eps)
  500. return ious