import random
import time
import numpy as np
"""
#单个iou
"""
def compute_iou2(rec1, rec2):
areas1 = (rec1[3] - rec1[1]) * (rec1[2] - rec1[0])
areas2 = (rec2[3] - rec2[1]) * (rec2[2] - rec2[0])
left = max(rec1[1],rec2[1])
right = min(rec1[3],rec2[3])
top = max(rec1[0], rec2[0])
bottom = min(rec1[2], rec2[2])
w = max(0, right-left)
h = max(0, bottom-top)
return w*h/(areas2+areas1-w*h)
def Ious(bbox, gt):
assert bbox.shape[0]>0, 'bbox len must>0'
assert gt.shape[0]>0, 'bbox len must>0'
"""
:param bbox: (n, 4)
:param gt: (m, 4)
:return: (n, m)
numpy 广播机制 从后向前对齐。 维度为1 的可以重复等价为任意维度
eg: (4,3,2) (3,2) (3,2)会扩充为(4,3,2)
(4,1,2) (3,2) (4,1,2) 扩充为(4, 3, 2) (3, 2)扩充为(4, 3,2) 扩充的方法为重复
广播会在numpy的函数 如sum, maximun等函数中进行
"""
lt = np.maximum(bbox[:, None, :2], gt[:, :2]) # left_top (x, y)
rb = np.minimum(bbox[:, None, 2:], gt[:, 2:]) # right_bottom (x, y)
wh = np.maximum(rb - lt , 0) # inter_area (w, h)
inter_areas = wh[:, :, 0] * wh[:, :, 1] # shape: (n, m)
box_areas = (bbox[:, 2] - bbox[:, 0] ) * (bbox[:, 3] - bbox[:, 1] )
gt_areas = (gt[:, 2] - gt[:, 0] ) * (gt[:, 3] - gt[:, 1] )
IoU = inter_areas / (box_areas[:, None] + gt_areas - inter_areas)
return IoU
if __name__ == '__main__':
data_a=[[1,1,3,3]]
data_a=[]
data_b=[[1,1,2,2],[2,2,4,4],[1,1,3,3],[3,3,4,4]]
ious= Ious(np.array(data_a), np.array(data_b))
print('IoU res')
print(ious.max())
ious=[]
start = time.time()
for data in data_b:
iou = compute_iou2(data_a[0], data)
ious.append(iou)
print('compute_iou2 res')
print(ious)
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/jacke121/article/details/121526711
内容来源于网络,如有侵权,请联系作者删除!