深度学习 — IoU python 实现
一、IoU 含义
IoU:IoU 的全称为交并比(Intersection over Union),IoU 计算的是 “预测框” 和 “真实框” 的交集和并集的比值。
图示如下:
二、算法实现
真实框和预测框根据实际情况,有如上四种位置关系。如果按照 暴力法 来求解 IoU 势必是一件特别麻烦而且不酷的事,如何帅气地实现 IoU 的算法,可以看我下面算法思想的环节。
算法思想:
我们以上图图2为例,IoU 的计算,是用真实框和预测框的交集面积 / 真实框和预测框的并集面积。所以关键的步骤需要求出交集部分的坐标,即上图中的A,B两点。
得到A,B坐标之后便可求出交集的宽高,来求出交集的面积。并集的面积 = 真实框的面积 + 预测框的面积 - 交集的面积。
问题便可解决
-
A,B坐标求法:
A:交集部分的左上坐标,来源于 真实框和预测框左上坐标中的较大值。 inter_upleft = np.maximum(box1[:2], box2[:2])
B:交集部分的左上坐标,来源于 真实框和预测框左上坐标中的较大值。 inter_botright = np.minimum(box1[2:], box2[2:]) -
交集的宽高求法:
inter_wh = inter_botright - inter_upleft
inter_wh = np.maximum(inter_wh, 0) :如果没有交集,宽高就赋值为0,解决图3,4的情况。
关于 np.maximum,np.minimum的解释如下:
np.maximum(X, Y, out=None):X 和 Y 逐位进行比较,选择最大值。
np.maximum(X, Y, out=None):X 和 Y 逐位进行比较,选择最小值。
完整代码如下:
#!/usr/bin/env python
# encoding: utf-8
'''
@Author : pentiumCM
@Email : 842679178@qq.com
@Software: PyCharm
@File : iou_utils.py
@Time : 2020/11/22 15:32
@desc : iou的工具模块
'''
import numpy as np
def iou(box1, box2):
"""
计算预测框和真实框之间的IoU
:param box1:预测框
:param box2: 真实框
:return:
"""
inter_upleft = np.maximum(box1[:2], box2[:2])
inter_botright = np.minimum(box1[2:], box2[2:])
inter_wh = inter_botright - inter_upleft
inter_wh = np.maximum(inter_wh, 0)
# 交集面积
inter = inter_wh[0] * inter_wh[1]
# 真实框的面积
area_gt = (box2[2] - box2[0]) * (box2[3] - box2[1])
# 预测框的面积
area_pred = (box1[2] - box1[0]) * (box1[3] - box1[1])
# 并集面积
union = area_gt + area_pred - inter
# 计算 IoU
iou_val = inter / union
return iou_val
if __name__ == '__main__':
box1 = np.array([50, 100, 150, 200])
box2 = np.array([100, 50, 200, 150])
iou_val = iou(box1, box2)
print(iou_val)