YOLOV3 将自己的txt转为XML,再将XML转为符合YOLO要求的txt格式

本文介绍如何将VOC格式数据集转换为YOLO格式,并提供了详细的Python代码实现。包括从VOC的XML标注文件转换到YOLO所需的TXT格式,以及如何划分训练集和验证集。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考链接:点击打开链接

我自己的数据集格式为filename lable xmin ymin xmax ymax

1 通过别的模板转换

VOC数据集的xml格式为:

<annotation>
  <folder>VOC2007</folder>
  <filename>000002.jpg</filename>    //文件名  
  <size>                            //图像尺寸(长宽以及通道数
    <width>335</width>
    <height>500</height>
    <depth>3</depth>
  </size>
  <object>        //检测到的物体
    <name>cat</name>    //物体类别
    <pose>Unspecified</pose>    //拍摄角度
    <truncated>0</truncated>    //是否被截断(0表示完整
    <difficult>0</difficult>    //目标是否难以识别(0表示容易识别)
    <bndbox>                    //bounding-box(包含左下角和右上角xy坐标)
      <xmin>139</xmin>
      <ymin>200</ymin>
      <xmax>207</xmax>
      <ymax>301</ymax>
    </bndbox>
  </object>
</annotation>

所以我们把它当作模板然后修改成自己的数据集。注意object 可能不止一个。

转换代码:

 
import copy
from lxml.etree import Element, SubElement, tostring, ElementTree
import cv2

# 修改为你自己的路径
template_file = 'G:\\dataset\\WJ-data\\anno.xml'
target_dir = 'G:\\dataset\\WJ-data\\Annotations\\'
image_dir = 'G:\\dataset\\train\\'  # 图片文件夹
train_file = 'G:\\dataset\\train.txt'  # 存储了图片信息的txt文件

with open(train_file) as f:
    trainfiles = f.readlines()  # 标注数据 格式(filename label x_min y_min x_max y_max)

file_names = []
tree = ElementTree()

for line in trainfiles:
    trainFile = line.split()
    file_name = trainFile[0]
    print(file_name)

    # 如果没有重复,则顺利进行。这给的数据集一张图片的多个框没有写在一起。
    if file_name not in file_names:
        file_names.append(file_name)
        lable = trainFile[1]
        xmin = trainFile[2]
        ymin = trainFile[3]
        xmax = trainFile[4]
        ymax = trainFile[5]

        tree.parse(template_file)
        root = tree.getroot()
        root.find('filename').text = file_name

        # size
        sz = root.find('size')
        im = cv2.imread(image_dir + file_name)#读取图片信息

        sz.find('height').text = str(im.shape[0])
        sz.find('width').text = str(im.shape[1])
        sz.find('depth').text = str(im.shape[2])

        # object 因为我的数据集都只有一个框
        obj = root.find('object')

        obj.find('name').text = lable
        bb = obj.find('bndbox')
        bb.find('xmin').text = xmin
        bb.find('ymin').text = ymin
        bb.find('xmax').text = xmax
        bb.find('ymax').text = ymax
        # 如果重复,则需要添加object框
    else:
        lable = trainFile[1]
        xmin = trainFile[2]
        ymin = trainFile[3]
        xmax = trainFile[4]
        ymax = trainFile[5]

        xml_file = file_name.replace('jpg', 'xml')
        tree.parse(target_dir + xml_file)#如果已经重复
        root = tree.getroot()

        obj_ori = root.find('object')

        obj = copy.deepcopy(obj_ori)  # 注意这里深拷贝

        obj.find('name').text = lable
        bb = obj.find('bndbox')
        bb.find('xmin').text = xmin
        bb.find('ymin').text = ymin
        bb.find('xmax').text = xmax
        bb.find('ymax').text = ymax
        root.append(obj)

    xml_file = file_name.replace('jpg', 'xml')
    tree.write(target_dir + xml_file, encoding='utf-8')

2.将xml转为符合YOLO的txt

标注文件.txt里的数据格式是这样的:

转换代码如下:

# box里保存的是ROI感兴趣区域的坐标(x,y的最大值和最小值)
# 返回值为ROI中心点相对于图片大小的比例坐标,和ROI的w、h相对于图片大小的比例
def convert(size, box):
    dw = 1./(size[0])
    dh = 1./(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)


# 对于单个xml的处理
def convert_annotation(image_add):
    # image_add进来的是带地址的.jpg
    #image_add = os.path.split(image_add,' ')[1]  # 截取文件名
    image_name = image_add.split()[0]
    print(image_name)
    image_name = image_name.replace('.jpg', '')  # 删除后缀,现在只有文件名
    in_file = open('G:\\dataset\\WJ-data\\Annotations\\' + image_name + '.xml')  # 图片对应的xml地址
    out_file = open('G:\\dataset\\WJ-data\\labels\\%s.txt' % (image_name), 'w')

    tree = ET.parse(in_file)
    root = tree.getroot()

    size = root.find('size')

    w = int(size.find('width').text)
    h = int(size.find('height').text)

    # 在一个XML中每个Object的迭代
    for obj in root.iter('object'):
        # iter()方法可以递归遍历元素/树的所有子元素
        difficult = obj.find('difficult').text
        cls = obj.find('name').text
        # 如果训练标签中的品种不在程序预定品种,或者difficult = 1,跳过此object
        if cls not in classes or int(difficult) == 1:
            continue
        cls_id = classes.index(cls)#这里取索引,避免类别名是中文,之后运行yolo时要在cfg将索引与具体类别配对
        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')


if not os.path.exists('G:\\dataset\\WJ-data\\labels\\'):#不存在文件夹
    os.makedirs('G:\\dataset\\WJ-data\\labels\\')

image_adds = open("G:\\dataset\\train.txt")
for image_add in image_adds:
    image_add = image_add.strip()
    convert_annotation(image_add)

print("Finished")

3.构建训练集与交叉验证集:

"""
分割训练集和验证集
分别存储了图片的路径
"""
from sklearn.model_selection import train_test_split

img_add = 'G:\\dataset\\train.txt'
data_set = [x.strip() for x in open(img_add).readlines()]

train_X, test_X = train_test_split(data_set, test_size=0.2, random_state=0)
print(train_X)
print(test_X)

train_file = open('G:\\dataset\\WJ-data\\train_file.txt', 'w')
for x in train_X:
    x = x.split(' ')[0]
    print(x)
    train_file.write('G:\\dataset\\train'+x+'\n')

test_file = open('G:\\dataset\\WJ-data\\valid_file.txt', 'w')
for x in test_X:
    x = x.split(' ')[0]
    test_file.write('G:\\dataset\\train'+x+'\n')

4. 生成类别名文件:

with open('G:\\dataset\\WJ-data\\obj.names', 'w') as f:
    for i in range(61):
        f.write(str(i)+'\n')

参考链接:

  1. 一次将自己的数据集制作成PASCAL VOC格式的惨痛经历
  2. 转换
  3. YOLOv3训练自己的数据(GPU版本)
  4. 【YOLO】数据集处理训练自己的数据集
### 将YOLOv5的txt标注文件转换为Pascal VOC XML格式 为了实现从YOLOv5的txt标注文件到Pascal VOC XML格式的转换,需要编写一段Python脚本。该过程涉及解析YOLO格式的文本文件并将其内容重新组织成符合Pascal VOC标准的XML结构。 #### 解析YOLO v5 txt 文件 YOLO v5使用的标签文件是以`.txt`结尾的小型纯文本文件,每行代表一个边界框,其格式如下: - `class_id center_x center_y width height` 这些数值均为相对于图像尺寸的比例值,在0至1之间[^1]。 #### 创建对应的Pascal VOC XML 结构 对于每一个YOLO `.txt`文件,都需要生成一个对应的`.xml`文件。每个XML文件应包含有关图像及其内含对象的具体描述。以下是创建这种映射关系的关键要素: - **filename**: 图像文件名。 - **size**: 包括宽度(`width`)、高度(`height`)和通道数(`depth`)。 - 对于每个对象(object),记录名称(name)即类别(class name), 边界框位置(bndbox): xmin, ymin, xmax 和 ymax。 #### Python 脚本示例 下面是一个简单的Python函数来完成上述任务: ```python import os from xml.etree.ElementTree import Element, SubElement, tostring from xml.dom.minidom import parseString def yolo_to_voc(yolo_path, image_info, output_dir): """ Convert YOLO format annotations to Pascal VOC format. :param yolo_path: Path of the .txt annotation file in YOLO format. :param image_info: Dictionary containing &#39;image_name&#39;, &#39;width&#39; and &#39;height&#39;. :param output_dir: Directory where generated .xml files will be saved. """ def prettify(elem): """Return a pretty-printed string representation of the element.""" rough_string = tostring(elem, &#39;utf-8&#39;) reparsed = parseString(rough_string) return reparsed.toprettyxml(indent=" ") with open(yolo_path, "r") as f: lines = f.readlines() root = Element(&#39;annotation&#39;) folder = SubElement(root, &#39;folder&#39;) folder.text = &#39;images&#39; filename = SubElement(root, &#39;filename&#39;) filename.text = image_info[&#39;image_name&#39;] size = SubElement(root, &#39;size&#39;) width = SubElement(size, &#39;width&#39;) width.text = str(image_info[&#39;width&#39;]) height = SubElement(size, &#39;height&#39;) height.text = str(image_info[&#39;height&#39;]) depth = SubElement(size, &#39;depth&#39;) depth.text = &#39;3&#39; for line in lines: parts = list(map(float, line.strip().split())) class_index = int(parts[0]) box_width = float(parts[3]) * image_info[&#39;width&#39;] box_height = float(parts[4]) * image_info[&#39;height&#39;] center_x = float(parts[1]) * image_info[&#39;width&#39;] - (box_width / 2.) center_y = float(parts[2]) * image_info[&#39;height&#39;] - (box_height / 2.) obj = SubElement(root, &#39;object&#39;) name = SubElement(obj, &#39;name&#39;) name.text = get_class_name_from_index(class_index) bndbox = SubElement(obj, &#39;bndbox&#39;) xmin = SubElement(bndbox, &#39;xmin&#39;) xmin.text = str(int(center_x)) ymin = SubElement(bndbox, &#39;ymin&#39;) ymin.text = str(int(center_y)) xmax = SubElement(bndbox, &#39;xmax&#39;) xmax.text = str(int(center_x + box_width)) ymax = SubElement(bndbox, &#39;ymax&#39;) ymax.text = str(int(center_y + box_height)) xml_str = prettify(root) save_path = os.path.join(output_dir, os.path.splitext(os.path.basename(yolo_path))[0]+&#39;.xml&#39;) with open(save_path, &#39;w&#39;) as out_file: out_file.write(xml_str) def get_class_name_from_index(index): # This function should map an integer index back to its corresponding label/class name, # which depends on your dataset&#39;s classes. For demonstration purposes only returns dummy value here. return [&#39;person&#39;][index] if __name__ == &#39;__main__&#39;: # Example usage img_details = {&#39;image_name&#39;: &#39;example.jpg&#39;, &#39;width&#39;: 640, &#39;height&#39;: 480} yolo_to_voc(&#39;./annotations/example.txt&#39;, img_details, &#39;./output_xmls/&#39;) ``` 此代码片段展示了如何读取YOLO格式的文本文件,并基于给定的图像信息构建相应的Pascal VOC XML文档。需要注意的是,实际应用中应当定义好`get_class_name_from_index()`方法以便正确获取类别的名字[^2]。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值