以四条线段表示该框,构造一个二进制的mask
因为框里的像素只需满足四个公式,在L4的下面,在L2的上面,在L1的左边,在L3的右边
两框的mask相与求交集,相或求并集,二者相除得到iou
import os
import numpy as np
def get_k(x1,y1,x2,y2,x3,y3,x4,y4):
k1=(y2-y1)/(x2-x1)
k2=(y3-y2)/(x3-x2)
k3=(y4-y3)/(x4-x3)
k4=(y4-y1)/(x4-x1)
bias1=y1-k1*x1
bias2 = y2 - k2 * x2
bias3 = y3 - k3 * x3
bias4 = y4 - k4 * x4
return k1,k2,k3,k4,bias1,bias2,bias3,bias4
def get_area(list1,width,height):
x1, y1, x2, y2, x3, y3, x4, y4=list1
k1,k2,k3,k4,bias1,bias2,bias3,bias4=get_k(x1,y1,x2,y2,x3,y3,x4,y4)
x_index=np.arange(0,width)
x_index=x_index.repeat(height,axis=-1).reshape(width,height).transpose()
y_index=np.arange(0,height)
y_index = y_index.repeat(width, axis=-1).reshape(height, width)
L1_statisfied=((y_index -bias1) /k1 > x_index)
L2_statisfied = (k2 * x_index + bias2 - y_index < 0)
L3_statisfied = ((y_index -bias3) /k3 < x_index)
L4_statisfied = (k4 * x_index + bias4 - y_index > 0)
image=L1_statisfied&L2_statisfied&L3_statisfied&L4_statisfied
return image
def get_iou(list1,list2):
width=max(list1[0],list1[2],list1[4],list1[6],list2[0],list2[2],list2[4],list2[6])
height=max(list1[1],list1[3],list1[5],list1[7],list2[1],list2[3],list2[5],list2[7])
image1=get_area(list1,width,height)
image2=get_area(list2,width,height)
jiaoji=image1&image2
jiaoji=np.array(jiaoji).astype(np.int)
bingji=image1|image2
bingji = np.array(bingji).astype(np.int)
iou=jiaoji.sum()/bingji.sum()
return iou
list1=[4,5,6,2,1,1,2,3]
list2=[4,5,6,2,1,1,2,3]
iou=get_iou(list1,list2)
print(iou)