目标检测ssd的.xml标记转换为yolo的.txt标记

引言

在进行目标检测项目时,首先是要通过labelImg软件将图片进行标记,此时在labelImg当中有三种对应的标记方式,分别对应labelImg中的:YOLO、CreateML、PascalVOC,他们的后缀分别为.txt、.json、.xml;

实战体验

在本次项目当中我们的目标检测模型是SSD,SSD模型要求标记的数据集的后缀为.xml,为了能够使得该标记的数据集也能够使用在YOLO模型当中,需要通过转换将.xml转换成.txt,但是在转换的过程中遇到如下问题:
YOLO当中由于数据经过标准化,标记的数据是在0~1这个区间当中,而SSD当中的数据并未通过标准化,因此需要定义相应的数据转换规则。

代码

代码如下:

import xml.etree.ElementTree as ET
from os import listdir, getcwd

classes = ["ori", "mouth","cap","smallcap"]

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
    return (x, y, w, h)


def convert_annotation():
    # 将.xml文件读取,保存到一个列表当中
    l1 = listdir("D:/图像SSD/05_不锈钢桶/20210909标识")
    # 一次循环取出列表当中的每个文件名
    for i in l1:
        name = i.split(".")[0]
        f = open('D:/图像SSD/05_不锈钢桶/20210909标识/'+i,encoding='UTF-8')
        xml_text = f.read()
        root = ET.fromstring(xml_text)
        f.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(cls)
                continue
            cls_id = classes.index(cls)
            print(cls_id)
            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 = open('D:/图像SSD/01_IBC桶/6/'+name+'.txt', 'a')
            # cls_id属于哪一类
            out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')


wd = getcwd()

if __name__ == '__main__':

    convert_annotation()

代码优势

我参考过网上其他代码,但是发现这些代码往往会有两类问题:
(1)首先,这类代码无法进行正规的标准化,即最终所转化的.txt文件并非是最终希望得到的数据格式
(2)其次,这些代码当所要转化的数据输入到.txt文件当中,往往都只能得到一条标记记录,这是因为在使用python的open()进行写入时,他们设置的参数往往是错误的,需要使用append的方式,将多个标签记录以追加的形式写入到.txt文件当中;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值