VOC转Yolo脚本

该脚本将VOC格式的XML注释文件转换为适用于Yolo目标检测模型的TXT格式。它遍历指定目录下的所有XML文件,提取类别信息并进行坐标转换。转换过程中,脚本会忽略不在预定义类别列表中的对象或标记为困难的对象。最终生成的TXT文件可直接用于Yolo模型的训练。

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

VOC转Yolo脚本

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

classes = ["ball",
"cylinder",
"square cage",
"cube",
"circle cage",
"human body",
"metal bucket",
"tyre"
          ]

def convert(size, box):
    dw = 1./(size[0])
    dh = 1./(size[1])
    x = (box[0] + box[1])/2.0 - 1
    y = (box[2] + box[3])/2.0 - 1
    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(rootpath,xmlname):
    xmlpath = rootpath + '/labels'
    xmlfile = os.path.join(xmlpath,xmlname)
    with open(xmlfile, "r") as in_file:
      txtname = xmlname[:-4]+'.txt'
      txtpath = rootpath + '/labelYOLOs'
      if not os.path.exists(txtpath):
        os.makedirs(txtpath)
      txtfile = os.path.join(txtpath,txtname)
      with open(txtfile, "w+") as out_file:
        tree=ET.parse(in_file)
        root = tree.getroot()
        size = root.find('size')
        w = int(size.find('width').text)
        h = int(size.find('height').text)
        out_file.truncate()
        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:
                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')


if __name__ == "__main__":
    rootpath= r'D:\2021TrainAndTestSet\test_A\test_A'
    xmlpath=rootpath+'/labels'
    list=os.listdir(xmlpath)
    for i in range(0,len(list)) :
        path = os.path.join(xmlpath,list[i])
        if ('.xml' in path)or('.XML' in path):
            convert_annotation(rootpath,list[i])
            print('done', i)
        else:
            print('not xml file',i)

 

### 将VOC格式换为YOLO格式的Python脚本 为了实现从Pascal VOCYOLO格式的数据集换,可以编写如下所示的Python脚本来完成此操作。该过程涉及读取XML文件中的边界框坐标并将其重新计算为中心点(x_center, y_center),宽度(width)以及高度(height)[^1]。 ```python import os from xml.etree import ElementTree as ET def convert_voc_to_yolo(xml_file_path, output_dir, image_width, image_height): tree = ET.parse(xml_file_path) root = tree.getroot() with open(os.path.join(output_dir, os.path.basename(xml_file_path).replace('.xml', '.txt')), 'w') as f: for obj in root.findall('object'): label = obj.findtext('name') bndbox = obj.find('bndbox') xmin = int(bndbox.findtext('xmin')) ymin = int(bndbox.findtext('ymin')) xmax = int(bndbox.findtext('xmax')) ymax = int(bndbox.findtext('ymax')) x_center = (xmin + xmax) / 2.0 / image_width y_center = (ymin + ymax) / 2.0 / image_height width = abs(xmax - xmin) / image_width height = abs(ymax - ymin) / image_height line = " ".join([str(label), str(x_center), str(y_center), str(width), str(height)]) f.write(line + '\n') if __name__ == '__main__': # 假设图像尺寸固定已知 img_wdith = 800 img_height = 600 voc_xml_files_directory = './Annotations' # 存储原始标注文件(.xml)的位置 destination_folder_for_txts = './labels' # 换后的标签保存位置 if not os.path.exists(destination_folder_for_txts): os.makedirs(destination_folder_for_txts) for file_name in os.listdir(voc_xml_files_directory): if file_name.endswith(".xml"): full_file_path = os.path.join(voc_xml_files_directory, file_name) convert_voc_to_yolo(full_file_path, destination_folder_for_txts, img_wdith, img_height) ``` 上述代码片段展示了如何遍历给定目录下的所有`.xml`文件,并逐一对它们执行换逻辑。需要注意的是,在实际应用中可能还需要考虑类别名称映射等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值