改下要检测的目标的名称,这名称具体叫啥要从xml文件里获得,不是自定义的。然后输入包含xml文件的文件夹的路径即可自动生成含txt文件的文件夹
import xml.etree.ElementTree as ET
import os
from os import listdir
from os.path import join
def convert(size, box): # size:(原图w,原图h) , box:(xmin,xmax,ymin,ymax)
dw = 1. / size[0] # 1/w
dh = 1. / size[1] # 1/h
x = (box[0] + box[1]) / 2.0 # 物体在图中的中心点x坐标
y = (box[2] + box[3]) / 2.0 # 物体在图中的中心点y坐标
w = box[1] - box[0] # 物体实际像素宽度
h = box[3] - box[2] # 物体实际像素高度
x = x * dw # 物体中心点x的坐标比(相当于 x/原图w)
w = w * dw # 物体宽度的宽度比(相当于 w/原图w)
y = y * dh # 物体中心点y的坐标比(相当于 y/原图h)
h = h * dh # 物体宽度的宽度比(相当于 h/原图h)
return (x, y, w, h) # 返回 相对于原图的物体中心点的x坐标比,y坐标比,宽度比,高度比,取值范围[0-1]
def convert_annotation(image_id):
in_file = open('dataSet/annotations/%s.xml' % (image_id), encoding='utf-8')
# 准备在对应的image_id 中写入对应的label,分别为
# <object-class> <x> <y> <width> <height>
out_file = open('dataSet/labels/%s.txt' % (image_id), 'w', encoding='utf-8')
# 解析xml文件
tree = ET.parse(in_file)
# 获得对应的键值对
root = tree.getroot()
# 获得图片的尺寸大小
size = root.find('size')
# 如果xml内的标记为空,增加判断条件
if size != None:
# 获得宽
w = int(size.find('width').text)
# 获得高
h = int(size.find('height').text)
# 遍历目标obj
for obj in root.iter('object'):
# 获得difficult ??
difficult = obj.find('difficult').text
# 获得类别 =string 类型
cls = obj.find('name').text
# 如果类别不是对应在我们预定好的class文件中,或difficult==1则跳过
if cls not in classes or int(difficult) == 1:
continue
# 通过类别名称找到id
cls_id = classes.index(cls)
# 找到bndbox 对象
xmlbox = obj.find('bndbox')
# 获取对应的bndbox的数组 = ['xmin','xmax','ymin','ymax']
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
float(xmlbox.find('ymax').text))
# print(image_id, cls, b)
# 带入进行归一化操作
# w = 宽, h = 高, b= bndbox的数组 = ['xmin','xmax','ymin','ymax']
bb = convert((w, h), b)
# bb 对应的是归一化后的(x,y,w,h)
# 生成 calss x y w h 在label文件中
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
def deleteFilesInFolder(folder):
file_list = os.listdir(folder)
for file_name in file_list:
file = folder + file_name
if os.path.isfile(file):
os.remove(file)
if __name__ == '__main__':
classes = ['hat', 'person'] # 要检测的目标的名称
pathOfLabels = 'dataSet/labels/'
if not os.path.exists(pathOfLabels):
os.makedirs(pathOfLabels) # labels文件夹如果不存在则创建
deleteFilesInFolder(pathOfLabels) # 确保存入txt文件前文件夹是空的
pathOfAnnotations = "dataSet/annotations" # 输入包含xml文件的文件夹的路径
xmlFiles = os.listdir(pathOfAnnotations)
image_ids = []
for xmlFile in xmlFiles:
image_ids.append(os.path.splitext(xmlFile)[0])
for image_id in image_ids:
convert_annotation(image_id)