通过计算理解iou

参考博客:目标检测之 IoU

在这里插入图片描述
二维情况下注意图中x和y轴的方向,交叉部分记住是上界的最小减去下界的最大就可以了。

一维情况:

import numpy as np
def iou(set_a , set_b):
    x1, x2 = set_a
    y1, y2 = set_b

    low = max(x1,y1)    ##交集下界
    high = min(x2, y2)  ##交集上界

    if   high-low<0 :  ##当上界小于下界时
        inter = 0
    else:
        inter = high - low
    union = (x2-x1)+(y2-y1)-inter    ##并集
    iou1 = inter/union
    return iou1
a = np.array([1,3])
b = np.array([2,4])
iou(a,b)
iou_output =iou(a,b)
print(iou_output)
##输出结果:
0.3333333333333333

二维情况:

import numpy as np
##借鉴一维的情况
## box[x1,y1,x2,y2]
## boxex[x1,y1,x2,y2]
def iou(box,boxes):
    w = min(box[2],boxes[2]) - max(box[0],boxes[0])
    h = min(box[3],boxes[3]) - max(box[1],boxes[1])
    if  h < 0 or w < 0:
        inter = 0
    else:
        inter = w *h
    union = (box[2]-box[0])*(box[3]-box[1]) + (boxes[2]-boxes[0])*(boxes[3]-boxes[1]) - inter
    iou = inter/union
    return iou
a= np.array([0,0,2,2])
b= np.array([1,0,3,1])
iou_out = iou(a,b)
print(iou_out)
##输出结果
0.2

二维情况下的另一种写法:

import numpy as np

def iou(box,boxes,isMin = False):
    ## box = [x1,y1,x2,y2,c]
    box_area = (box[2] - box[0]) * (box[3] -box[1])
    boxes_area = (boxes[:,2] - boxes[:,0]) * (boxes[:,3] - boxes[:,1])
    xx1 = np.maximum(box[0],boxes[:,0])
    yy1 = np.maximum(box[1], boxes[:, 1])
    xx2 = np.minimum(box[2], boxes[:, 2])
    yy2 = np.minimum(box[3], boxes[:, 3])

    w = np.maximum(0,xx2-xx1)
    h = np.maximum(0,yy2-yy1)
    inter = w*h
    if isMin : ##最小面积
        over = np.true_divide(inter,np.minimum(box_area,boxes_area))
    else:      ##交并比#
         over = np.true_divide(inter,(box_area+boxes_area-inter))
    return over
a= np.array([0,0,2,2])
b= np.array([[1,0,3,1]])
iou_out = iou(a,b)
print(iou_out)
#结果[0.2 0.2]

注意,这里boxes需要导入一个多维的,不然会报以下错误:
IndexError: too many indices for array
出现这样的情况你因为你矩阵的维度出现了冗余情况,比如你把一组数放入矩阵,矩阵默认的维度是2,但是你其实只有一列数,因此可以先用np.shape函数查看你的矩阵维度,是否出现了(n,)这样的情况。

发布了61 篇原创文章 · 获赞 17 · 访问量 2991

猜你喜欢

转载自blog.csdn.net/qq_35027690/article/details/103515670
IOU