目标检测,已知坐标,如何计算 IoU 值

假设有两个矩形框,其坐标情况如下表所示

左上角右下角宽度高度
矩形框1 ( x 1 , y 1 ) (x_1,y_1) (x1,y1) ( x 2 , y 2 ) (x_2, y_2) (x2,y2) w = x 2 − x 1 w=x_2-x_1 w=x2x1 h = y 2 − y 1 h=y_2-y_1 h=y2y1
矩形框2 ( x 1 ′ , y 1 ′ ) (x_1', y_1') (x1,y1) ( x 2 ′ , y 2 ′ ) (x_2', y_2') (x2,y2) w ′ = x 2 ′ − x 1 ′ w'=x_2'-x_1' w=x2x1 h ′ = y 2 ′ − y 1 ′ h'=y_2'-y_1' h=y2y1
交集框 ( max ⁡ ( x 1 , x 1 ′ ) , max ⁡ ( y 1 , y 1 ′ ) ) (\max(x_1, x_1'), \max(y_1, y_1')) (max(x1,x1),max(y1,y1)) ( min ⁡ ( x 2 , x 2 ′ ) , min ⁡ ( y 2 , y 2 ′ ) ) (\min(x_2, x_2'), \min(y_2, y_2')) (min(x2,x2),min(y2,y2)) W I W_I WI H I H_I HI

交集框的宽度为 W I = max ⁡ [ min ⁡ ( x 2 , x 2 ′ ) − max ⁡ ( x 1 , x 1 ′ ) , 0 ] W_I = \max[\min(x_2, x_2')-\max(x_1,x_1'), 0] WI=max[min(x2,x2)max(x1,x1),0]
交集框的高度为 H I = max ⁡ [ min ⁡ ( y 2 , y 2 ′ ) − max ⁡ ( y 1 , y 1 ′ ) , 0 ] H_I= \max[\min(y_2, y_2') - \max(y_1, y_1'), 0] HI=max[min(y2,y2)max(y1,y1),0]
交集框的面积为 A I = W I × H I A_I = W_I \times H_I AI=WI×HI

当两个矩形框不相交时, W I = 0 W_I=0 WI=0 或者 H I = 0 H_I=0 HI=0,此时交集框的面积 A I = 0 A_I=0 AI=0

并集的面积为 A U = w × h + w ′ × h ′ A_U = w \times h + w' \times h' AU=w×h+w×h

交并比 I o U = A I A U \mathrm{IoU} = \frac{A_I}{A_U} IoU=AUAI

python 代码

def iou(x1, y1, x2, y2, x1_hat, y1_hat, x2_hat, y2_hat):
	w = x2 - x1
	h = y2 - y1
	w_hat = x2_hat - x1_hat 
	h_hat = y2_hat - y1_hat 
	w_i = max(min(x2, x2_hat) - max(x1, x1_hat), 0) 
	h_i = max(min(y2, y2_hat) - max(y1, y1_hat), 0) 
	A_i = w_i * h_i
	A_u = w * h + w_hat * h_hat
	return A_i / A_u
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页