import os
import xml.etree.ElementTree as ET
#程序功能:批量修改VOC数据集中xml标签文件的标签名称
def changelabelname(inputpath):
listdir = os.listdir(inputpath)
for file in listdir:
if file.endswith('xml'):
file = os.path.join(inputpath,file)
print(file)
tree = ET.parse(file)
root = tree.getroot()
for object1 in root.findall('object'):
for bboxs in object1.findall('bndbox'):
xmin=ymin=xmax=ymax=0
xmin_ori=ymin_ori=xmax_ori=ymax_ori=0
for bbox_xmin in bboxs.findall('xmin'):
xmin_ori=int(bbox_xmin.text)
xmin=int(bbox_xmin.text)-250
for bbox_ymin in bboxs.findall('ymin'):
ymin_ori=int(bbox_ymin.text)
ymin=int(bbox_ymin.text)-200
for bbox_xmax in bboxs.findall('xmax'):
xmax_ori=int(bbox_xmax.text)
xmax=int(bbox_xmax.text)-250
for bbox_ymax in bboxs.findall('ymax'):
ymax_ori=int(bbox_ymax.text)
ymax=int(bbox_ymax.text)-200
area_1=(ymax_ori-ymin_ori)*(xmax_ori-xmin_ori)
if (xmin_ori>1850 or ymin_ori>1386 or xmax_ori<250 or ymax_ori<200):
xmin=ymin=xmax=ymax=str(0)
else:
if xmin<0:
xmin=0
if ymin<=0:
ymin=0
if xmax>1550:
xma=1550
if ymax>1336:
ymax=1336
area_2=(ymin-ymax)*(xmin-xmax)
if area_1!=0:
if(area_2/area_1)>0.8:
xmin=str(xmin)
ymin=str(ymin)
xmax=str(xmax)
ymax=str(ymax)
else:
xmin=ymin=xmax=ymax=str(0)
else:
xmin=ymin=xmax=ymax=str(0)
for bbox in bboxs.findall('xmin'):
bbox.text =xmin
tree.write(file,encoding='utf-8')
for bbox in bboxs.findall('ymin'):
bbox.text = ymin
tree.write(file,encoding='utf-8')
for bbox in bboxs.findall('xmax'):
bbox.text =xmax
tree.write(file,encoding='utf-8')
for bbox in bboxs.findall('ymax'):
bbox.text =ymax
tree.write(file,encoding='utf-8')
else:
pass
if __name__ == '__main__':
inputpath = r"C:\Users\lenovo\Desktop\整合\xml" #此处替换为自己的路径
changelabelname(inputpath)
print(1)
来源:CSDN
作者:xiaoleige0713
链接:https://blog.csdn.net/xiaoleige0713/article/details/103683398