import numpy as np box1 = np.array([[0,0,100,100],[0,0,100,100]]) box2 = np.array([[50,50,100,100],[0,0,80,80]]) def calc_iou(boxes1, boxes2): # calculate the left up point & right down point lu = np.maximum(boxes1[..., :2], boxes2[..., :2]) rd = np.minimum(boxes1[..., 2:], boxes2[..., 2:]) # 计算机交集面积 intersection = np.maximum(0.0, rd - lu) inter_square = intersection[..., 0] * intersection[..., 1] # 计算每个box的面积 square1 = (boxes1[..., 2] - boxes1[..., 0])* (boxes1[..., 3] - boxes1[..., 1]) square2 = (boxes2[..., 2] - boxes2[..., 0])* (boxes2[..., 3] - boxes2[..., 1]) #计算并集面积 union_square = np.maximum(square1 + square2 - inter_square, 1e-10) #numpy 后面两个参数是分别表示最大值与最小值 return np.clip(inter_square / union_square, 0.0, 1.0) iou = calc_iou(box1,box2) print(iou)