完整代码如下:
import xml.etree.ElementTree as ET
import os
# 标签类别
classes = ["DefectPin", "NormalPin"]
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
def convert(size, box):
dw = 1. / size[0]
dh = 1. / size[1]
x = (box[0] + box[1]) / 2.0 # (x_min + x_max) / 2.0
y = (box[2] + box[3]) / 2.0 # (y_min + y_max) / 2.0
w = box[1] - box[0] # x_max - x_min
h = box[3] - box[2] # y_max - y_min
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
def convert_annotation(image_id):
in_file = open('./data_insutors/标签/%s.xml' % image_id, encoding='UTF-8') # .xml文件
out_file = open('./data_insutors/labels/%s.txt' % image_id, 'w') # 生成.txt文件
tree = ET.parse(in_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
for obj in root.iter('object'):
cls = obj.find('name').text
if cls not in classes:
continue
cls_id = classes.index(cls)
xml_box = obj.find('bndbox')
b = (float(xml_box.find('xmin').text), float(xml_box.find('xmax').text), float(xml_box.find('ymin').text),
float(xml_box.find('ymax').text))
bb = convert((w, h), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
xml_path = os.path.join(CURRENT_DIR, './data_insutors/标签') # .xml文件所在目录
img_xml = os.listdir(xml_path)
for img_xml in img_xml:
label_name = img_xml.rsplit('.', 1)[0]
convert_annotation(label_name)
需要修改的信息例举如下
1、获取标签的类别信息
2、指定xml文件和txt文件路径
3、获取xml文件所在目录
4、获取生成的txt文件名(需要与对应的图像文件名一致),具体文件名获取参考如下,需要根据实际的图像文件名进行获取:
5、修改完以上4步,即可将xml文件转化为对应的txt文件。