序言
面试过程中遇到的问题,如何对2Dbox、3Dbox和旋转box求iou。
2D Box计算代码
def cal_2dbox(box1, box2):
"""
box format: xyxy
"""
x1 = max(box1[0], box2[0])
y1 = max(box1[1], box2[1])
x2 = min(box1[2], box2[2])
y2 = min(box1[3], box2[3])
union = (x2 - x1) * (y2 - y1)
area1 = (box1[2]-box1[0]) * (box1[3]-box1[1])
area2 = (box2[2]-box2[0]) * (box2[3]-box2[1])
iou = union/(area1+area2-union)
return iou
3D Box计算代码
def cal_2dbox(box1, box2):
"""
box format: xyxy
"""
x1 = max(box1[0], box2[0])
y1 = max(box1[1], box2[1])
x2 = min(box1[2], box2[2])
y2 = min(box1[3], box2[3])
union = (x2 - x1) * (y2 - y1)
area1 = (box1[2]-box1[0]) * (box1[3]-box1[1])
area2 = (box2[2]-box2[0]) * (box2[3]-box2[1])
iou = union/(area1+area2-union)
return iou
旋转 Box计算代码
def cal_skewbox(box1, box2):
"""
box format: cxcywh angle
"""
area1 = box1[2]*box1[3]
area2 = box2[2]*box2[3]
box1_inp = ((box1[0], box1[1]), (box1[2], box1[3]), box1[4])
box2_inp = ((box2[0], box2[1]), (box2[2], box2[3]), box2[4])
int_pts = cv2.rotatedRectangleIntersection(tuple(box1_inp), tuple(box2_inp))[1]
#order_pts = cv2.convexHull(int_pts, returnPoints=True)
union = cv2.contourArea(int_pts)
iou = union/(area1+area2-union)
return iou
结果
if __name__ == "__main__":
#2D
box1_2d = [50, 100, 100, 200]
box2_2d = [50, 50, 100, 200]
iou_2d = cal_2dbox(box1_2d, box2_2d)
print("二维box的计算结果:", iou_2d)
#3D
box1_3d = [50, 100, 30, 100, 200, 60]
box2_3d = [50, 50, 30, 100, 200, 90]
iou_3d = cal_3dbox(box1_3d, box2_3d)
print("三维box的计算结果:", iou_3d)
#skew
box1_skew = [50, 100, 100, 200, 0]
box2_skew = [50, 100, 100, 200, 90]
iou_skew = cal_skewbox(box1_skew, box2_skew)
print("旋转box的计算结果:", iou_skew)
终端结果:
二维box的计算结果: 0.6666666666666666
三维box的计算结果: 0.3333333333333333
旋转box的计算结果: 0.3333333333333333