一維iou
二維
import numpy as npdef iou_1d(set_a, set_b):# 獲得集合A和B的邊界 x1, x2 = set_ay1, y2 = set_b# 計算交集的上下界low = max(x1,y1)high - min(x2, y2)# 計算交集if high - low < 0:inter = 0else:inter = high - low# 計算并集union = (x2 -x1) + (y2 - y1) - inter# 計算IoUiou = inter / unionreturn ioudef iou_2d(box1,box2):'''二維IoU的計算:注意圖像坐標系的原點一般在左上角,x方向朝右,y方向朝下box的表示:[top, left, bottom, right]box的表示分別對應:[y1,x1,y2,x2]'''in_h = min(box1[2],box2[2]) - max(box1[0],box2[0])in_w = min(box1[3],box2[3]) - max(box1[1],box2[1])inter = 0 if in_h < 0 or in_w < 0 else in_h * in_wunion = (box1[2] - box1[0]) * (box1[3] - box1[1]) + (box2[2] - box2[0]) * (box2[3] - box2[1]) - interiou = inter / unionreturn ioudef iou_3d(box1,box2):'''3D IoU計算box表示形式:[x1,y1,z1,x2,y2,z2] 分別是兩對角點的坐標'''in_w = min(box1[3],box2[3]) - max(box1[0],box2[0])in_l = min(box1[4],box2[4]) - max(box1[1],box2[1])in_h = min(box1[5],box2[5]) - max(box1[2],box2[2])inter = 0 if in_w < 0 or in_l < 0 or in_h < 0 else in_w * in_l * in_hunion = (box1[3] - box1[0]) * (box1[4] - box1[1]) * (box1[5] - box1[2]) + (box2[3] - box2[0]) * (box2[4] - box2[1]) * (box2[5] - box2[2]) - interiou = inter / unionreturn iouif __name__ == '__main__':box1 = [0,0,0,1,1,1]box2 = [0.5,0.5,0.5,1.5,1.5,1.5]print(iou_3d(box1,box2))