一.IoU的概念
IoU是一种测量在特定数据集中检测相应物体准确度的一个标准。IoU是一个简单的测量标准,只要是在输出中得出一个预测范围(bounding boxex)的任务都可以用IoU来进行测量。
用来测量预测框图和真实框的相近程度,取值范围【0,1】,越接近1表明预测结果越接近真实值。
公式(1)
如图1所示:为真实值和预测值的交集,为二者的并集。
图1 IOU示意图
具体结果如图2所示:图2中第三幅图结果优于前面两幅。
图2 IOU结果图
二、spyder中Iou的python代码实现
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 1 22:05:48 2021
@author: lenovo
"""
import numpy as np
import cv2
def CountIOU(A,B):
#A B分别代表预测框和真实框
# eg A = [50,50,300,300] 左上角50,50和右下角300,300坐标
#计算交集坐标
x_top=max(A[0],B[0])
y_top=max(A[1],B[1])
x_bottle=min(A[2],B[2])
y_bottle=min(A[3],B[3])
#计算交集面积
interArea=(x_bottle-x_top)*(y_bottle-y_top)
# 计算并集面积 :areaA+areaB-interArea
areaA=(A[2]-A[0])*(A[3]-A[1])
areaB=(B[2]-B[0])*(B[3]-B[1])
unArea=areaA+areaB-interArea
iou=interArea/unArea
print('iou=',iou)
return iou
if __name__=='__main__':
A = [50,50,300,300]
B = [60,60,320,320]
img=np.zeros((512,512,3),np.uint8)
img.fill(255)
cv2.rectangle(img,(A[0],A[1]),(A[2],A[3]),(0,255,0),5)
cv2.rectangle(img,(B[0],B[1]),(B[2],B[3]),(255,0,0),5)
IOU=CountIOU(A,B)
font=cv2.FONT_ITALIC
cv2.putText(img,"IOU=%.5f"%IOU,((A[2]+A[0])//2-20,(A[1]+A[3])//2),font,0.8,(0,0,0))
cv2.imshow("IOU Test",img)
cv2.waitKey()
cv2.destroyAllWindows()
运行结果: