Pytorch/Python计算交并比IOU(IU)代码(批量算IOU)

Pytorch/Python计算交并比IOU(IU)代码(批量算IOU)_第1张图片

检测准确率用IOU来计算

这也是用左上右下两个点坐标来表示矩形

boxA=[x1,y1,x2,y2]

boxB=[x3,y3,x4,y4]

Pytorch/Python计算交并比IOU(IU)代码(批量算IOU)_第2张图片

 坐标关系是这样的,零点是在左上角的,不是右下角!!

def IOU(boxA, boxB):
    boxA = [int(x) for x in boxA]
    boxB = [int(x) for x in boxB]

    xA = max(boxA[0], boxB[0])
    yA = max(boxA[1], boxB[1])
    xB = min(boxA[2], boxB[2])
    yB = min(boxA[3], boxB[3])

    interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)

    boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
    boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)
    
    iou = interArea / float(boxAArea + boxBArea - interArea)

    return iou

写法2

输入是这种形式的: [103, 825, 103, 987, 726, 987, 726, 825]

分别是四个点的w和h(先w后h), 即(x1,y1,x2,y2,x3,y3,x4,y4)

import numpy as np
import Polygon as plg

def get_union(pa, pb):
    pa_area = pa.area()
    pb_area = pb.area()
    return pa_area + pb_area - get_intersection(pa, pb)

def get_intersection(pa, pb):
    pInt = pa & pb
    if len(pInt) == 0:
        return 0
    else:
        return pInt.area()

a = np.array([103, 825, 103, 987, 726, 987, 726, 825])
b = np.array([101, 828, 731, 828, 731, 996, 101, 996])

poly_a = plg.Polygon(a.reshape(-1, 2))
poly_b = plg.Polygon(b.reshape(-1, 2))

union = get_union(poly_a, poly_b)
inter = get_intersection(poly_a, poly_b)
IOU = inter / (union + 1e-6)
print(IOU)

③如果是与坐标轴平行的举行,可以用torchvision内置的函数

这个函数可以批量算IOU

 torchvision.ops.box_iou(boxes1, boxes2)
  • boxes1 (Tensor[N4]) – first set of boxes

  • boxes2 (Tensor[M4]) – second set of boxes

bbox是(x1, y1, x2, y2) 的形式

import torch
import torchvision
 
a =  torch.tensor([[2,3.1,7,5]]) 
b =  torch.tensor([[3,4,8,4.8]]) 
result = torchvision.ops.box_iou(a,b)
print(result)

import torch
import torchvision
 
a =  torch.tensor([[2,3.1,7,5],[3,4,8,4.8],[4,4,5.6,7],[0.1,0,8,1]]) 
b =  torch.tensor([[2,3.1,7,5],[3,4,8,4.8],[4,4,5.6,7],[0.1,0,8,1]]) 
result = torchvision.ops.box_iou(a,b)
print(result)

Pytorch/Python计算交并比IOU(IU)代码(批量算IOU)_第3张图片

你可能感兴趣的:(IOU)