def iou(a, b): """ :param a:4*M*1 left,top,right,bottom :param b:4*1*N left,top,right,bottom :return: """ aleft, atop, aright, abottom = [a[i] for i in range(4)] bleft, btop, bright, bbottom = [b[i] for i in range(4)] cross_left = np.maximum(aleft, bleft) cross_top = np.maximum(atop, btop) cross_right = np.minimum(aright, bright) cross_bottom = np.minimum(abottom, bbottom) # 如果没有交集就需要裁切(M*N) cross_area = (cross_right - cross_left + 1).clip(0) * (cross_bottom - cross_top + 1).clip(0) union_area = (aright - aleft + 1) * (abottom - atop + 1) + (bright - bleft + 1) * (bbottom - btop + 1) - cross_area return cross_area / union_area if __name__ == '__main__': a = np.arange(0, 12).reshape(4, -1, 1) b = np.arange(12, 24).reshape(4, 1, -1) iou(a,b)