通过计算理解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,)这样的情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

通信仿真爱好者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值