xml数据集格式转yolov5txt格式

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!')

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值