Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. import numpy as np
  2.  
  3.  
  4. def iou(a, b):
  5. lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])
  6. rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])
  7.  
  8. area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2)
  9. area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)
  10. area_b = np.prod(b[:, 2:] - b[:, :2], axis=1)
  11. return area_i / (area_a[:, np.newaxis] + area_b - area_i)
  12.  
  13.  
  14. class Rect(tuple):
  15. __slots__ = list()
  16.  
  17. def __new__(cls, rect):
  18. return super().__new__(cls, rect)
  19.  
  20. def LTRB(left, top, right, bottom):
  21. return Rect((left, top, right, bottom))
  22.  
  23. def LTWH(left, top, width, height):
  24. return Rect((
  25. left,
  26. top,
  27. left + width,
  28. top + height))
  29.  
  30. def XYWH(center_x, center_y, width, height):
  31. return Rect((
  32. center_x - width / 2,
  33. center_y - height / 2,
  34. center_x + width / 2,
  35. center_y + height / 2))
  36.  
  37. def astype(self, dtype):
  38. return Rect(map(dtype, self))
  39.  
  40. @property
  41. def left(self):
  42. return self[0]
  43.  
  44. @property
  45. def top(self):
  46. return self[1]
  47.  
  48. @property
  49. def right(self):
  50. return self[2]
  51.  
  52. @property
  53. def bottom(self):
  54. return self[3]
  55.  
  56. @property
  57. def width(self):
  58. return self.right - self.left
  59.  
  60. @property
  61. def height(self):
  62. return self.bottom - self.top
  63.  
  64. def __and__(self, other):
  65. left = max(self.left, other.left)
  66. top = max(self.top, other.top)
  67. right = min(self.right, other.right)
  68. bottom = min(self.bottom, other.bottom)
  69.  
  70. if left < right and top < bottom:
  71. return Rect.LTRB(left, top, right, bottom)
  72. else:
  73. return None
  74.  
  75. def __mul__(self, k):
  76. try:
  77. kx, ky = k
  78. except ValueError:
  79. kx, ky = k, k
  80. return Rect.LTRB(
  81. self.left * kx,
  82. self.top * ky,
  83. self.right * kx,
  84. self.bottom * ky)
  85.  
  86. @property
  87. def area(self):
  88. return self.width * self.height
  89.  
  90. def iou(self, other):
  91. intersect = self & other
  92. if intersect is None:
  93. return 0
  94. return intersect.area \
  95. / (self.area + other.area - intersect.area)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement