Code
def batch_iou(a, b, epsilon=1e-5):
""" Given two arrays `a` and `b` where each row contains a bounding
box defined as a list of four numbers:
[x1,y1,x2,y2]
where:
x1,y1 represent the upper left corner
x2,y2 represent the lower right corner
It returns the Intersect of Union scores for each corresponding
pair of boxes.
Args:
a: (numpy array) each row containing [x1,y1,x2,y2] coordinates
b: (numpy array) each row containing [x1,y1,x2,y2] coordinates
epsilon: (float) Small value to prevent division by zero
Returns:
(numpy array) The Intersect of Union scores for each pair of bounding
boxes.
"""
# COORDINATES OF THE INTERSECTION BOXES
= np.array([a[:, 0], b[:, 0]]).max(axis=0)
x1 = np.array([a[:, 1], b[:, 1]]).max(axis=0)
y1 = np.array([a[:, 2], b[:, 2]]).min(axis=0)
x2 = np.array([a[:, 3], b[:, 3]]).min(axis=0)
y2
# AREAS OF OVERLAP - Area where the boxes intersect
= (x2 - x1)
width = (y2 - y1)
height
# handle case where there is NO overlap
< 0] = 0
width[width < 0] = 0
height[height
= width * height
area_overlap
# COMBINED AREAS
= (a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1])
area_a = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])
area_b = area_a + area_b - area_overlap
area_combined
# RATIO OF AREA OF OVERLAP OVER COMBINED AREA
= area_overlap / (area_combined + epsilon)
iou return iou