看代码还是挺好理解的。
def overlap_ratio(rect1, rect2):
'''
Compute overlap ratio between two rects
- rect: 1d array of [x,y,w,h] or
2d array of N x [x,y,w,h]
'''
if rect1.ndim == 1:#ndim返回数组的维度。
rect1 = rect1[None, :]#如果维度为1,那么将维度变为2
if rect2.ndim == 1:
rect2 = rect2[None, :]
left = np.maximum(rect1[:, 0], rect2[:, 0])#left中存储的是rect1与rect2第一列进行比较后的最大值,是一个长度为N的数组。其实,存储的是最左边的点的x较大的值。——>交叉部分的左边点的x的坐标
right = np.minimum(rect1[:, 0] + rect1[:, 2], rect2[:, 0] + rect2[:, 2])#同上,存储的为右边的点小的x的坐标——>交叉部分右边点的坐标。left-right即为交叉部分的长度。
top = np.maximum(rect1[:, 1], rect2[:, 1])#下面点大的y值——>交叉部分,下面的y值
bottom = np.minimum(rect1[:, 1] + rect1[:, 3], rect2[:, 1] + rect2[:, 3])#上面点小的y值——>交叉部分上面的y值。bottom-top即为交叉部分的宽度。
intersect = np.maximum(0, right - left) * np.maximum(0, bottom - top)#求得重叠面积。
union = rect1[:, 2] * rect1[:, 3] + rect2[:, 2] * rect2[:, 3] - intersect#求得两个框的并集的面积。
iou = np.clip(intersect / union, 0, 1)#计算iou
return iou