python实现iou计算

发布时间 2023-07-15 12:30:02作者: Picassooo
import numpy as np

def iou(box1, box2):
    x1, y1, x2, y2 = box1 
    w1, h1, w2, h2 = box2 
    left_max = max(x1, w1)
    right_min = min(x2, w2)
    top_max = max(y1, h1)
    bot_min = min(y2, h2)
    if left_max >= right_min or top_max >= bot_min:
        return 0 
    else:
        intersection = (right_min - left_max) * (bot_min - top_max)
        union = (x2-x1) * (y2 - y1) + (w2 - w1) * (h2 - h1) - intersection
        return intersection / union

b1 = np.array([0, 0, 200, 200])
b2 = np.array([100, 100, 500, 500])
out = iou(b1, b2)   # out = 0.0526