import xml.etree.ElementTree as ET
import glob
classes = ["TL"]
# 归一化操作
def convert(size, box):
dw = 1.0 / size[0]
dh = 1.0 / size[1]
x = (box[0] + box[1]) / 2.0
y = (box[2] + box[3]) / 2.0
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
# 这里定义数据保存的精度
x = round(x, 6)
w = round(w, 6)
y = round(y, 6)
h = round(h, 6)
return x, y, w, h
def convert_annotation(image_name):
# xml文件路径
xml_file = open('H:/jlj/yolov5-6.1-TL-master/TL_data/val/xmls/' + image_name[:-3] + 'xml')
# 转换后txt文件存放路径
txt_file = open('H:/jlj/yolov5-6.1-TL-master/TL_data/val/labels/' + image_name[:-3] + 'txt', 'w')
xml_text = xml_file.read()
root = ET.fromstring(xml_text)
xml_file.close()
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:
print('do not use %s' % cls)
continue
cls_id = classes.index(cls)
xml_box = obj.find('bndbox')
points = (float(xml_box.find('xmin').text), float(xml_box.find('xmax').text),
float(xml_box.find('ymin').text), float(xml_box.find('ymax').text))
local = convert((w, h), points)
txt_file.write(str(cls_id) + " " + " ".join([str(a) for a in local]) + '\n')
if __name__ == '__main__':
# 图像数据集路径
for image_path in glob.glob(r"H:\jlj\yolov5-6.1-TL-master\TL_data\val\images\*.jpg"):
# image_path.split('\\'):将image_path以'\\'进行分割[list]
image_name = image_path.split('\\')[-1]
convert_annotation(image_name)
print('Done convert!')
xml数据集格式转yolov5txt格式
猜你喜欢
转载自blog.csdn.net/weixin_42182534/article/details/125680565
今日推荐
周排行