bbox_overlaps.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import numpy as np
  3. def bbox_overlaps(bboxes1,
  4. bboxes2,
  5. mode='iou',
  6. eps=1e-6,
  7. use_legacy_coordinate=False):
  8. """Calculate the ious between each bbox of bboxes1 and bboxes2.
  9. Args:
  10. bboxes1 (ndarray): Shape (n, 4)
  11. bboxes2 (ndarray): Shape (k, 4)
  12. mode (str): IOU (intersection over union) or IOF (intersection
  13. over foreground)
  14. use_legacy_coordinate (bool): Whether to use coordinate system in
  15. mmdet v1.x. which means width, height should be
  16. calculated as 'x2 - x1 + 1` and 'y2 - y1 + 1' respectively.
  17. Note when function is used in `VOCDataset`, it should be
  18. True to align with the official implementation
  19. `http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCdevkit_18-May-2011.tar`
  20. Default: False.
  21. Returns:
  22. ious (ndarray): Shape (n, k)
  23. """
  24. assert mode in ['iou', 'iof']
  25. if not use_legacy_coordinate:
  26. extra_length = 0.
  27. else:
  28. extra_length = 1.
  29. bboxes1 = bboxes1.astype(np.float32)
  30. bboxes2 = bboxes2.astype(np.float32)
  31. rows = bboxes1.shape[0]
  32. cols = bboxes2.shape[0]
  33. ious = np.zeros((rows, cols), dtype=np.float32)
  34. if rows * cols == 0:
  35. return ious
  36. exchange = False
  37. if bboxes1.shape[0] > bboxes2.shape[0]:
  38. bboxes1, bboxes2 = bboxes2, bboxes1
  39. ious = np.zeros((cols, rows), dtype=np.float32)
  40. exchange = True
  41. area1 = (bboxes1[:, 2] - bboxes1[:, 0] + extra_length) * (
  42. bboxes1[:, 3] - bboxes1[:, 1] + extra_length)
  43. area2 = (bboxes2[:, 2] - bboxes2[:, 0] + extra_length) * (
  44. bboxes2[:, 3] - bboxes2[:, 1] + extra_length)
  45. for i in range(bboxes1.shape[0]):
  46. x_start = np.maximum(bboxes1[i, 0], bboxes2[:, 0])
  47. y_start = np.maximum(bboxes1[i, 1], bboxes2[:, 1])
  48. x_end = np.minimum(bboxes1[i, 2], bboxes2[:, 2])
  49. y_end = np.minimum(bboxes1[i, 3], bboxes2[:, 3])
  50. overlap = np.maximum(x_end - x_start + extra_length, 0) * np.maximum(
  51. y_end - y_start + extra_length, 0)
  52. if mode == 'iou':
  53. union = area1[i] + area2 - overlap
  54. else:
  55. union = area1[i] if not exchange else area2
  56. union = np.maximum(union, eps)
  57. ious[i, :] = overlap / union
  58. if exchange:
  59. ious = ious.T
  60. return ious