voc转yolo代码

本文介绍了一个Python脚本,用于将VOC(VisualObjectClasses)2007格式的XML标注文件转换为YOLO所需的txt格式,便于模型训练。脚本通过解析XML,提取对象位置和类别信息并进行格式转换。

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

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
 
 
def convert(size, box):
    x_center = (box[0] + box[1]) / 2.0
    y_center = (box[2] + box[3]) / 2.0
    x = x_center / size[0]
    y = y_center / size[1]
    w = (box[1] - box[0]) / size[0]
    h = (box[3] - box[2]) / size[1]
    return (x, y, w, h)
 
 
def convert_annotation(xml_files_path, save_txt_files_path, classes):
    xml_files = os.listdir(xml_files_path)
    print(xml_files)
    for xml_name in xml_files:
        print(xml_name)
        xml_file = os.path.join(xml_files_path, xml_name)
        out_txt_path = os.path.join(save_txt_files_path, xml_name.split('.')[0] + '.txt')
        out_txt_f = open(out_txt_path, 'w')
        tree = ET.parse(xml_file)
        root = tree.getroot()
        size = root.find('size')
        w = int(size.find('width').text)
        h = int(size.find('height').text)
 
        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))
            # b=(xmin, xmax, ymin, ymax)
            print(w, h, b)
            bb = convert((w, h), b)
            out_txt_f.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
 
 
if __name__ == "__main__":
    # 需要转换的类别,需要一一对应
    classes1 = ['boat', 'cat']
    # 2、voc格式的xml标签文件路径
    xml_files1 = r'C:\Users\86159\Desktop\VOC2007\Annotations'
    # 3、转化为yolo格式的txt标签文件存储路径
    save_txt_files1 = r'C:\Users\86159\Desktop\VOC2007\label'
 
    convert_annotation(xml_files1, save_txt_files1, classes1)
### Pascal VOC格式与YOLO格式的差异 Pascal VOC格式通常使用XML文件来存储标注信息,而YOLO格式则采用更简洁的文本文件(`.txt`)。两者的主要区别在于数据结构和坐标表示方式。Pascal VOC使用绝对坐标表示边界框的位置,而YOLO格式使用归一化后的相对坐标[^1]。 ### 换步骤说明 在换过程中,需要从Pascal VOC格式提取以下信息:类名、边界框的左上角和右下角坐标(`xmin, ymin, xmax, ymax`),并将其换为YOLO格式所需的归一化中心点坐标和宽高比例(`x_center, y_center, width, height`)[^2]。 以下是实现换的具体代码示例: ```python import xml.etree.ElementTree as ET import os def convert_voc_to_yolo(xml_file, output_dir, class_names): tree = ET.parse(xml_file) root = tree.getroot() # 获取图像尺寸 size = root.find('size') width = float(size.find('width').text) height = float(size.find('height').text) # 构建输出文件名 txt_file = os.path.join(output_dir, os.path.splitext(os.path.basename(xml_file))[0] + '.txt') with open(txt_file, 'w') as f: for obj in root.iter('object'): class_name = obj.find('name').text if class_name not in class_names: continue # 如果类别不在预定义列表中,则跳过 class_id = class_names.index(class_name) # 获取边界框坐标 bbox = obj.find('bndbox') xmin = float(bbox.find('xmin').text) ymin = float(bbox.find('ymin').text) xmax = float(bbox.find('xmax').text) ymax = float(bbox.find('ymax').text) # 计算YOLO格式的归一化坐标 x_center = (xmin + xmax) / 2.0 / width y_center = (ymin + ymax) / 2.0 / height width_yolo = (xmax - xmin) / width height_yolo = (ymax - ymin) / height # 写入YOLO格式文件 f.write(f"{class_id} {x_center:.6f} {y_center:.6f} {width_yolo:.6f} {height_yolo:.6f}\n") # 示例调用 class_names = ['cat', 'dog', 'person'] # 定义类别名称 convert_voc_to_yolo('path/to/voc.xml', 'path/to/output', class_names) ``` 上述代码将读取Pascal VOC格式的XML文件,并将其换为YOLO格式的文本文件。注意,`class_names`列表应包含所有可能的类别名称,类别ID是基于该列表的索引值[^3]。 ### 注意事项 - 确保输入的XML文件路径正确。 - 在生成YOLO格式文件时,确保输出目录存在。 - 类别名称必须与训练时使用的类别名称一致,否则会导致模型无法正确解析标注信息[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值