计算标注的数据框之间的遮挡。针对xml格式的voc标签。
代码如下:
#-*- coding:UTF-8 -*-
import os.path
import glob
import re
import xml.etree.ElementTree as ET
import numpy as np
from PIL import Image
'''
计算数据集中每一个xml文件的多个目标框之间的交并比
2019.3.1
nansbas
'''
#ipu计算
def calcIOU(one_x, one_y, one_w, one_h, two_x, two_y, two_w, two_h):
if((abs(one_x - two_x) < ((one_w + two_w) / 2.0)) and (abs(one_y - two_y) < ((one_h + two_h) / 2.0))):
lu_x_inter = max((one_x - (one_w / 2.0)), (two_x - (two_w / 2.0)))
lu_y_inter = min((one_y + (one_h / 2.0)), (two_y + (two_h / 2.0)))
rd_x_inter = min((one_x + (one_w / 2.0)), (two_x + (two_w / 2.0)))
rd_y_inter = max((one_y - (one_h / 2.0)), (two_y - (two_h / 2.0)))
inter_w = abs(rd_x_inter - lu_x_inter)
inter_h = abs(lu_y_inter - rd_y_inter)
inter_square = inter_w * inter_h
union_square = (one_w * one_h) + (two_w * two_h) - inter_square
calcIOU = inter_square / union_square * 1.0
print("calcIOU:", calcIOU)
else:
print("No intersection!")
return calcIOU
if __name__ == "__main__":
x_path='C:/Users/nansbas/Desktop/01/'
x_list=os.listdir(x_path)
a={}
for file in x_list:
a[file]={}
tree = ET.parse(x_path+file)
num=0
root = tree.getroot()
for object in root.findall('object'):
a[file]['{}'.format(num)]={}
for bndbox in object.findall('bndbox'):
a[file]['{}'.format(num)]['x'] = int(bndbox.find('xmin').text)
a[file]['{}'.format(num)]['w'] = int(bndbox.find('xmax').text)-int(bndbox.find('xmin').text)
a[file]['{}'.format(num)]['y'] = int(bndbox.find('ymin').text)
a[file]['{}'.format(num)]['h'] = int(bndbox.find('ymax').text)-int(bndbox.find('ymin').text)
num+=1
a[file]['obj_num']=num
all_iou=0
for file in x_list:
iou=0
if a[file]['obj_num'] >= 1:
for i in range(a[file]['obj_num']):
x = a[file]['{}'.format(i)]['x']
w = a[file]['{}'.format(i)]['w']
y = a[file]['{}'.format(i)]['y']
h = a[file]['{}'.format(i)]['h']
for j in range(a[file]['obj_num']):
if i != j:
x1 = a[file]['{}'.format(j)]['x']
w1 = a[file]['{}'.format(j)]['w']
y1 = a[file]['{}'.format(j)]['y']
h1 = a[file]['{}'.format(j)]['h']
iou+=calcIOU(x,y,w,h,x1,y1,w1,h1)
all_iou += calcIOU(x,y,w,h,x1,y1,w1,h1)
else:
continue
else:
continue
miou=iou/a[file]['obj_num']
print("file name is {}/n: Miou={}".format(file,miou))
print('all_iou = {}'.format(all_iou))