VOC标签格式转yolo格式并划分训练集和测试集

目录

一、了解VOC数据格式

 1、Annotations目录

 2. JPEGImages目录

二、YOLO格式

三、VOC标签格式转yolo格式并划分训练集和测试集


一、了解VOC数据格式

 Pascal VOC数据集下载地址:The PASCAL Visual Object Classes Homepage

介绍一下VOC 数据集下载后的目录结构:

 1、Annotations目录

目录存放xml文件:

Annotations文件夹中存放的是xml格式的标签文件,每一个xml文件都对应于JPEGImages文件夹中的一张图片,包含了图片的重要信息:图片的名称图片中object的类别及其bounding box坐标

文件内容如下

<annotation>
	<folder>images</folder>
	<filename>HW57-2 (3).jpg</filename>
	<path>C:\Users\lrj\Pictures\开裂标定\images\HW57-2 (3).jpg</path>
	<source>
		<database>Unknown</database>
	</source>
	<size>
		<width>1008</width>
		<height>1397</height>
		<depth>3</depth>
	</size>
	<segmented>0</segmented>
	<object>
		<name>close</name>
		<pose>Unspecified</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>133</xmin>
			<ymin>748</ymin>
			<xmax>244</xmax>
			<ymax>854</ymax>

 2. JPEGImages目录

存放的是数据集的原图片,像素尺寸大小不一。这里是自己的数据集。

二、YOLO格式

yolo标注格式保存在.txt文件中,一共5个数据,用空格隔开,举例说明如下图所示:

三、VOC标签格式转yolo格式并划分训练集和测试集

标注数据最好选择VOC格式,因为VOC格式包含更多的信息。

下面介绍格式转换:

代码运行结果:

 

 

 

产生一个VOCdevkit目录,其下包含多个目录,其中YOLOLables文件夹是存储所有转换好的yolo标签文件,其他的目录或看文件夹名便知,或已在前面介绍过。这样可以与yolov5训练无缝衔接

对应的是

yolov5项目中,有关于数据集的yaml文件,把yolov5_train.txt、yolov5_val.txt的完整路径写好即可

转换代码:

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

classes = ["open", "close"] # 自己标注的数据集的类别
#classes=["ball"]



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  # bbox宽度与图像宽度比值
    y = y*dh  # 中心点纵坐标与图像高度比值
    h = h*dh  # bbox高度与图像高度比值
    return (x,y,w,h)

def convert_annotation(input, output):
    in_file = open(input)
    out_file = open(output, 'w')
    tree=ET.parse(in_file) # Python xml 读取
    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'): # 对于每个bbox
        difficult = obj.find('difficult').text
        cls = obj.find('name').text # 目标类别
        if cls not in classes or int(difficult) == 1: # 如果类别错误,则continue
            continue
        cls_id = classes.index(cls) # 获得类别索引
        xmlbox = obj.find('bndbox') # bbpx
        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) # voc转yolo
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n') # cls_id centerx centery w h
    in_file.close()
    out_file.close()


def generate_diretorys(wd):

    data_base_dir = os.path.join(wd, "VOCdevkit/")
    os.mkdir(data_base_dir)

    work_sapce_dir = os.path.join(data_base_dir, "VOC2007/")
    os.mkdir(work_sapce_dir)

    annotation_dir = os.path.join(work_sapce_dir, "Annotations/")
    os.mkdir(annotation_dir)

    image_dir = os.path.join(work_sapce_dir, "JPEGImages/")
    os.mkdir(image_dir)

    yolo_labels_dir = os.path.join(work_sapce_dir, "YOLOLabels/")
    os.mkdir(yolo_labels_dir)

    yolov5_images_dir = os.path.join(data_base_dir, "images/")
    os.mkdir(yolov5_images_dir)

    yolov5_labels_dir = os.path.join(data_base_dir, "labels/")
    os.mkdir(yolov5_labels_dir)

    yolov5_images_train_dir = os.path.join(yolov5_images_dir, "train/")
    os.mkdir(yolov5_images_train_dir)

    yolov5_images_test_dir = os.path.join(yolov5_images_dir, "val/")
    os.mkdir(yolov5_images_test_dir)

    yolov5_labels_train_dir = os.path.join(yolov5_labels_dir, "train/")
    os.mkdir(yolov5_labels_train_dir)

    yolov5_labels_test_dir = os.path.join(yolov5_labels_dir, "val/")
    os.mkdir(yolov5_labels_test_dir)


def transform(images_dir, annotations_dir, split_val_rate, wd):
    train_file = open(os.path.join(wd, "yolov5_train.txt"), 'w') # 记载训练集图片目录的txt文件
    val_file = open(os.path.join(wd, "yolov5_val.txt"), 'w') # # 记载测试集图片目录的txt文件
    train_file.close()
    val_file.close()
    train_file = open(os.path.join(wd, "yolov5_train.txt"), 'a')
    val_file = open(os.path.join(wd, "yolov5_val.txt"), 'a')


    assert os.path.exists(images_dir), "path '{}' does not exist.".format(images_dir)
    assert  os.path.exists(annotations_dir), "path '{}' does not exist.".format(annotations_dir)

    assert os.path.exists(os.path.join(wd, "VOCdevkit", "labels", "val")), "val path does not exist"
    assert os.path.exists(os.path.join(wd, "VOCdevkit", "labels", "train")), "train path does not exist"




    list_imgs = os.listdir(images_dir) # list image files  所有图片名字
    random.seed(0)
    num = len(list_imgs)
    eval_index = random.sample(list_imgs, k=int(num*split_val_rate))

    another_images_dir = os.path.join(wd, "VOCdevkit", "VOC2007", "JPEGImages")
    assert os.path.exists(another_images_dir), "dir '{}' does not exist".format(another_images_dir)
    another_yolo_labels_dir = os.path.join(wd, "VOCdevkit", "VOC2007", "YOLOLabels")
    assert os.path.exists(another_yolo_labels_dir), "dir '{}' does not exist".format(another_yolo_labels_dir)
    another_Annotations_dir = os.path.join(wd, "VOCdevkit", "VOC2007", "Annotations")
    assert os.path.exists(another_Annotations_dir), "'{}' path does not exist".format(another_Annotations_dir)

    for index, image in enumerate(list_imgs):
        if image in eval_index:
            image_path = os.path.join(images_dir, image)
            new_image_path = os.path.join(wd, "VOCdevkit","images", "val", image)
            copy(image_path, new_image_path)

            image_id, extention = os.path.splitext(image)
            annotation_name = image_id + ".xml"
            annotation_dir = os.path.join(annotations_dir, annotation_name)
            new_annation_name = image_id + ".txt"
            new_annotation_dir = os.path.join(wd, "VOCdevkit", "labels", "val", new_annation_name)
            convert_annotation(annotation_dir,new_annotation_dir)

            val_file.write(new_image_path +"\n")
            copy(image_path, another_images_dir)
            copy(new_annotation_dir, another_yolo_labels_dir)
            copy(annotation_dir, another_Annotations_dir)




        else:
            image_path = os.path.join(images_dir, image)
            new_image_path = os.path.join(wd, "VOCdevkit","images", "train", image)
            copy(image_path, new_image_path)

            image_id, extention = os.path.splitext(image)
            annotation_name = image_id + ".xml"
            annotation_dir = os.path.join(annotations_dir, annotation_name)
            new_annation_name = image_id + ".txt"
            new_annotation_dir = os.path.join(wd, "VOCdevkit", "labels", "train", new_annation_name)
            convert_annotation(annotation_dir,new_annotation_dir)

            train_file.write(new_image_path + "\n")
            copy(image_path, another_images_dir)
            copy(new_annotation_dir, another_yolo_labels_dir)
            copy(annotation_dir, another_Annotations_dir)

        print("\r processing [{}/{}]".format(index+1, num), end="")



    train_file.close()
    val_file.close()

def check_img_label(images_dir, labels_dir):
    assert os.path.exists(images_dir), "'{}' does not exist!".format(images_dir)
    assert os.path.exists(labels_dir), "'{}' dose not exist!".format(labels_dir)

    list_imgs = os.listdir(images_dir) # list image files  所有图片名字

    for img in list_imgs:
        img_id, extension = os.path.splitext(img)
        img_dir = os.path.join(images_dir, img)

        label_name = img_id + ".xml"
        label_dir = os.path.join(labels_dir, label_name)

        if not os.path.exists(labels_dir):
            os.remove(img_dir)
            os.remove(label_dir)


if __name__ == "__main__":
    wd = "/home/jason/work/my-datasets/"
    generate_diretorys(wd=wd) # 生成多级目录
    raw_images_dir = "/home/jason/work/my-datasets/images" # 图片所在目录
    raw_annotions_dir = "/home/jason/work/my-datasets/annotions" # voc 格式标签文件坐在目录
    check_img_label(images_dir=raw_images_dir, labels_dir=raw_annotions_dir) # 检查图片名字与标签文件名字是否一一对应
    transform(images_dir=raw_images_dir, annotations_dir=raw_annotions_dir,split_val_rate=0.2, wd=wd) # VOC转yolo,并划分训练集、测试集

      

参考:

目标检测数据集标注-VOC格式_AI学长的博客-CSDN博客

YOLO数据格式说明与转换_yolo格式_lokvke的博客-CSDN博客

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 将voc标签格式换为yolo格式的步骤如下: 1. 读取voc标签文件,获取每个标注框的坐标信息和类别信息。 2. 将坐标信息换为yolo格式的相对坐标,即中心点坐标和宽高的比例。 3. 将类别信息换为yolo格式的类别编号,从开始。 4. 将换后的标签信息保存到对应的yolo标签文件中。 划分训练集测试集的步骤如下: 1. 将所有数据集按照一定比例分为训练集测试集,通常是将数据集的70%作为训练集,30%作为测试集。 2. 将训练集测试集的图像和标签文件分别存放在不同的文件夹中。 3. 在训练时,使用训练集进行模型训练测试集用于测试模型的性能。 ### 回答2: 介绍 VOC标签格式YOLO标签格式是目标检测任务中最常见的两种标签格式VOC标签格式是指PASCAL VOC数据集使用的标签格式,通常为XML格式。而YOLO标签格式是指Darknet团队开发的YOLO算法使用的标签格式,通常为txt格式。本文将介绍如何将VOC标签格式换为YOLO标签格式,并且如何划分训练集测试集VOC标签格式YOLO标签格式 VOC标签格式包含每个图像中的所有目标的信息,并且每个目标都包含类别、边界框位置和部分属性(如难度)等信息。从VOC标签格式换为YOLO标签格式的关键是要将边界框位置信息归一化为0到1之间的值。YOLO标签格式只需要目标类别和边界框的中心坐标和宽度/高度比例即可。具体步骤如下: 1. 读取VOC标签格式文件,获取每张图像中的目标数量、类别、位置和部分属性等信息。 2. 对每个目标进行边界框位置信息的归一化,计算边界框中心坐标和宽度/高度比例。 3. 将每个目标的类别和边界框信息换为YOLO标签格式并保存为txt格式的文件。 划分训练集测试集 划分训练集测试集的目的是为了评估模型的性能。训练集用于训练模型,而测试集用于评估模型在新数据上的表现。一般来说,训练集测试集应该互不重叠,并且测试集应该具有与训练集相似的数据分布。 划分训练集测试集的方法很多,常见的有随机划分、按文件名划分和按目录划分等。其中,按目录划分是最常见的方法。一般来说,数据集应该先按类别分组,然后再按目录划分。例如,对于VOC数据集,可以将JPEGImages目录下的图像和Annotations目录下的标签文件分别放在同一个目录中,并按类别分组。然后,可以将每个类别的数据集划分训练集测试集,建议将测试集的比例设置为20-30%。 总结 将VOC标签格式换为YOLO标签格式划分训练集测试集是目标检测任务中非常重要的一步。这可以使得我们能够使用更多的数据来训练模型,并且能够准确评估模型在新数据上的表现。划分训练集测试集的方法很多,需要根据数据集的特点进行选择。 ### 回答3: 首先,VOC标签格式YOLO标签格式有一些不同之处,需要进行换。VOC标签格式是一种XML文件格式,其中包含图片的基本信息、标注信息以及对象的类别、坐标等信息。而YOLO标签格式是一种txt文件格式,每一行都表示一张图片,包含该图片中物体的类别以及bounding box坐标信息等。 VOC格式标签YOLO格式标签可以使用Python编程语言来完成。具体操作步骤如下: 1、读取XML格式VOC标签文件,获取图片的基本信息和对象的类别、坐标信息等。 2、根据YOLO标签格式的要求,将图片基本信息和对象类别信息分别存储到txt文件的不同行中。 3、将VOC标签格式中的坐标信息换为YOLO标签格式的坐标信息。 4、将所有信息存储到txt文件中。 划分训练集测试集也需要一定的步骤: 1、将所有图片按比例分配给训练集测试集。 2、根据所选比例,将标签文件也分配到训练集测试集的文件夹中。 3、在训练测试之前,可以随机化数据集的顺序。 4、在使用YOLO进行训练测试时,需要使用train.txt和val.txt来载入训练测试集。 在实际的操作中,可以使用Python编写脚本来自动完成上述操作,节省时间和减少人工操作的误差。同时,开发者还可以根据需要进行自定义,如结合TensorFlow、Keras等框架进行模型训练和优化,以获得更准确的目标检测和分割结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值