目标检测——IoU 计算

本文介绍了一种用于评估目标检测算法中预测框与真实框重叠程度的指标——交并比(IoU)的计算方法。文章首先从一维情况出发,逐步过渡到二维情况,并通过具体实例展示了如何使用Python代码实现IoU的计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Iou 的计算

我们先考虑一维的情况:令 \(A = [x_1,x_2], B = [y_1, y_2]\),若想要 \(A\)\(B\) 有交集,需要满足如下情况:
685754-20190328230226115-1099323701.jpg

简言之,要保证 \(A\)\(B\) 的最大值中最小的那个减去它们中的最小值中最大的那个即可获得公共部分,代码实现如下:

class Anchor:
    def __init__(self, base_size=16):
        self.base_size = base_size  # 滑动窗口的大小
        if not base_size:
            raise ValueError("Invalid base_size: {}.".format(base_size))
        self._anchor = np.array([1, 1, self.base_size, self.base_size]) - 1

    @property
    def anchor(self):
        return self._anchor

    @anchor.setter
    def anchor(self, new_anchor):
        self._anchor = new_anchor

    @property
    def w(self):
        '''
        锚框的宽度
        '''
        return self.anchor[2] - self.anchor[0] + 1

    @property
    def h(self):
        '''
        锚框的高度
        '''
        return self.anchor[3] - self.anchor[1] + 1

    @property
    def size(self):
        '''
        锚框的面积
        '''
        return self.w * self.h

    @property
    def _whctrs(self):
        """
        Return x center, and y center for an anchor (window). 锚框的中心坐标
        """
        x_ctr = self.anchor[0] + 0.5 * (self.w - 1)
        y_ctr = self.anchor[1] + 0.5 * (self.h - 1)
        return np.array([x_ctr, y_ctr])

    @staticmethod
    def _coordinate(aspect, ctr):
        '''
        依据宽高组合计算锚框的坐标
        '''
        k = (aspect - 1) / 2
        return np.concatenate([ctr - k, ctr + k], axis=1)

先创建一个可以用来做运算的计算器,然后在此基础上计算二维的 IoU,即

def iou(anchor, anchor1):
    A = Anchor()
    B = Anchor()
    A.anchor = anchor
    B.anchor = anchor1
    T = np.stack([A.anchor, B.anchor])
    xmin, ymin, xmax, ymax = np.split(T, 4, axis=1)
    w = xmax.min() - xmin.max()
    h = ymax.min() - ymin.max()
    I = w * h
    U = A.size + B.size - I
    return I / U

下面举一例子,并可视化:

685754-20190328232423448-1369894650.png

img = np.ones((128 ,300, 3))  # 图片
anchor = [ 12.,   8., 195., 103.]
anchor1 = [ 28.,   8., 211., 103.]
iou(anchor, anchor1)

最终结果为:

0.8151364126804707

转载于:https://www.cnblogs.com/q735613050/p/10618558.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值