XML格式标签
<annotation>
<folder>images</folder>
<filename>0001.jpg</filename>
<path>/Users/Ralf/Downloads/smoking/images/0001.jpg</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>460</width>
<height>480</height>
<depth>1</depth>
</size>
<segmented>0</segmented>
<object>
<name>smoking</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>156</xmin>
<ymin>112</ymin>
<xmax>367</xmax>
<ymax>333</ymax>
</bndbox>
</object>
</annotation>
XML格式大家应该很熟悉,无论是学后端的,还是算法,XML是一种数据的配置格式或者数据的存储格式。对于目标检测来说,我们所需的信息是XML中的<name>标签,它规定了目标检测中的类别索引。<xmin>、<ymin>、<xmax>、<ymax>分别代表左上角右上角的坐标。
YOLO格式标签
0 0.5684782608695652 0.4635416666666667 0.45869565217391306 0.46041666666666664
五个值分别代表类别索引、归一化的中心点x坐标、归一化的中心点y坐标、归一化的框宽度,归一化的框高度。所以想要快速训练yolo,就需要把xml格式的标签改为yolo格式的标签,当然也有的代码中包含标签转换的代码,视情况而定。
转换代码
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
import random
from shutil import copyfile
# 根据自己的需求设置类文件
classes = ['类别1name','类别2name']
# Training ratio
# 根据自己的需求设置训练比
# TRAIN_RATIO = 70
# Traversing folders
def clear_hidden_files(path):
dir_list = os.listdir(path)
for i in dir_list:
abspath = os.path.join(os.path.abspath(path), i)
if os.path.isfile(abspath):
if i.startswith("._"):
os.remove(abspath)
else:
clear_hidden_files(abspath)
# Normalization of width and height is performed
# Size is the width and height of the original image
def convert(size, box):
dw = 1. / size[0]
dh = 1. / size[1]
# Get Center Point
x = (box[0] + box[1]) / 2.0
y = (box[2] + box[3]) / 2.0
# Calculate width and height
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
# Parsing xml files
def convert_annotation(image_id):
in_file = open('C:/Users/Desktop/Annotations/%s.xml' % image_id, 'rb')
out_file = open('C:/Users/Desktop/labels/%s.txt' % image_id, 'a')
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'):
difficult = obj.find('difficult').text
cls = obj.find('name').text
# if cls not in classes or int(difficult) == 1:
if cls not in classes:
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
float(xmlbox.find('ymax').text))
bb = convert((w, h), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
in_file.close()
out_file.close()
if __name__ == '__main__':
base_path = r"C:\Users\Desktop\数据集"
xml_list = os.listdir(base_path)
for item in xml_list:
imageid=item.split('.')[0]
# print(imageid)
convert_annotation(imageid)