目标检测之IoU
本博客主要作为本人学习记录,如果错误烦请指正哟~
IoU作为目标检测算法性能mAP计算的一个非常重要的函数,其计算过程是怎样的?
1. IoU原理
IoU全程交并比(Intersection over Union),计算的是“预测的边框”和“真实的边框”的交集和并集的比值。
预测边框的并集容易计算,即两个边框面积相加减去交集,但是交集不易计算。在计算交集时你首先想到的是,根据两个框的相对位置来计算交集,如图:
但是这样程序分支太多,设计较为麻烦了,所以可以先从一维角度考虑计算交集,如图所示:
假设集合A为[x1, x2], 集合B为[y1, y2], 则计算A,B集合的交集为:
交集上边界min:min {x1, y1}
交集下边界max:max{x2, y2}
交集:max - min,(max-min)<=0,则无交集
2. 代码示例
def iou(setA,setB):
'''
一维iou的计算
'''
x1,x2 = setA
y1,y2 = setB
low = max(x1,y1)
high = min(x2,y2)
#intersection
if high-low<0:
inter=0
else:
inter=high-low
#union
union=(x2-x1)+(y2-y1)-inter
iou=inter/union
return iou
二维计算:
def iou(box1, box2):
'''
两个框(二维)的 iou 计算
相当于两个一维相乘
注意:边框以左上为原点
box:[top, left, bottom, right]
'''
in_h = min(box1[2], box2[2]) - max(box1[0], box2[0])
in_w = min(box1[3], box2[3]) - max(box1[1], box2[1])
inter = 0 if in_h<0 or in_w<0 else in_h*in_w
union = (box1[2] - box1[0]) * (box1[3] - box1[1]) + \
(box2[2] - box2[0]) * (box2[3] - box2[1]) - inter
iou = inter / union
return iou
TensorFlow计算IoU
import tensorflow as tf
def IoU_calculator(x, y, w, h, l_x, l_y, l_w, l_h):
"""calaulate IoU
Args:
x: net predicted x
y: net predicted y
w: net predicted width
h: net predicted height
l_x: label x
l_y: label y
l_w: label width
l_h: label height
Returns:
IoU
"""
# convert to coner
x_max = x + w/2
y_max = y + h/2
x_min = x - w/2
y_min = y - h/2
l_x_max = l_x + l_w/2
l_y_max = l_y + l_h/2
l_x_min = l_x - l_w/2
l_y_min = l_y - l_h/2
# calculate the inter
inter_x_max = tf.minimum(x_max, l_x_max)
inter_x_min = tf.maximum(x_min, l_x_min)
inter_y_max = tf.minimum(y_max, l_y_max)
inter_y_min = tf.maximum(y_min, l_y_min)
inter_w = inter_x_max - inter_x_min
inter_h = inter_y_max - inter_y_min
inter = tf.cond(tf.logical_or(tf.less_equal(inter_w,0), tf.less_equal(inter_h,0)),
lambda:tf.cast(0,tf.float32),
lambda:tf.multiply(inter_w,inter_h))
# calculate the union
union = w*h + l_w*l_h - inter
IoU = inter / union
return IoU
参考:https://blog.csdn.net/u014061630/article/details/82818112