天天看點

用numpy計算IOU

import numpy as np

box1 = np.array([[10, 10, 50, 50],
                [70, 70, 120, 120]])

box2 = np.array([[10, 10, 50, 50],
                [100, 100, 150, 150],
                [80, 80, 160, 160],
                [130, 130, 200, 200]])


def iou_match_grid(box1, box2):

    x11, y11, x12, y12 = np.split(box1, 4, axis=1)
    x21, y21, x22, y22 = np.split(box2, 4, axis=1)

    xa = np.maximum(x11, np.transpose(x21))
    xb = np.minimum(x12, np.transpose(x22))
    ya = np.maximum(y11, np.transpose(y21))
    yb = np.minimum(y12, np.transpose(y22))

    area_inter = np.maximum(0, (xb - xa + 1)) * np.maximum(0, (yb - ya + 1))

    area_1 = (x12 - x11 + 1) * (y12 - y11 + 1)
    area_2 = (x22 - x21 + 1) * (y22 - y21 + 1)
    area_union = area_1 + np.transpose(area_2) - area_inter

    iou = area_inter / area_union

    return iou


print(iou_match_grid(box1, box2))