voc数据集与yolo数据集格式 互相转换

 1. voc转yolo

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

sets = ['trainval','test']

classes = [ 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog',
         'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor' ] # voc的20个类别


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)


def convert_annotation(image_id):
    in_file = open('./model/dataset/VOCdevkit/VOC2007/Annotations/%s.xml' % (image_id))
    #填原来voc数据集xml标注数据文件所在路径
    out_file = open('./labels/test/%s.txt' % (image_id), 'w')
    #填转换后的yolov5需要labels文件所在路径
    tree = ET.parse(in_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))
        bb = convert((w, h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')

# if __name__ == "__main__":


wd = getcwd()

for image_set in sets:
    if not os.path.exists('./labels/'):
        os.makedirs('./labels/')
    #创建转换后labels存放文件路径

    image_ids = open('./model/dataset/VOCdevkit/VOC2007/ImageSets/Main/%s.txt' % (image_set)).read().strip().split()
    #list_file = open('./%s.txt' % (image_set), 'w')

    for image_id in image_ids:
        #list_file.write('dataset/VOCdevkit/VOC2007/JPEGImages/%s.jpg\n' % (image_id))
        convert_annotation(image_id)
    list_file.close()

以上代码可以将voc格式的xml注释文件转换成yolov5格式的labels注释文件,只需要将路径改为自己的,直接运行即可。

2.yolo转voc

import os
import glob
from PIL import Image

voc_annotations = 'voc_test/Annotations/'
yolo_txt = 'yolo_test/labels/'
img_path = 'yolo_test/images/'

labels = [ 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog',
         'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor' ] # label for datasets


# 图像存储位置
src_img_dir = img_path 
# 图像的txt文件存放位置


src_txt_dir = yolo_txt
src_xml_dir = voc_annotations

img_Lists = glob.glob(src_img_dir + '/*.jpg')

img_basenames = []
for item in img_Lists:
    img_basenames.append(os.path.basename(item))

img_names = []
for item in img_basenames:
    temp1, temp2 = os.path.splitext(item)
    img_names.append(temp1)

for img in img_names:
    im = Image.open((src_img_dir + '/' + img + '.jpg'))
    width, height = im.size

    # 打开txt文件
    gt = open(src_txt_dir + '/' + img + '.txt').read().splitlines()
    print(gt)
    if gt:
        # 将主干部分写入xml文件中
        xml_file = open((src_xml_dir + '/' + img + '.xml'), 'w')
        xml_file.write('<annotation>\n')
        xml_file.write('    <folder>VOC2007</folder>\n')
        xml_file.write('    <filename>' + str(img) + '.jpg' + '</filename>\n')
        xml_file.write('    <size>\n')
        xml_file.write('        <width>' + str(width) + '</width>\n')
        xml_file.write('        <height>' + str(height) + '</height>\n')
        xml_file.write('        <depth>3</depth>\n')
        xml_file.write('    </size>\n')

        # write the region of image on xml file
        for img_each_label in gt:
            spt = img_each_label.split(' ')  # 这里如果txt里面是以逗号‘,’隔开的,那么就改为spt = img_each_label.split(',')。
            print(f'spt:{spt}')
            xml_file.write('    <object>\n')
            xml_file.write('        <name>' + str(labels[int(spt[0])]) + '</name>\n')
            xml_file.write('        <pose>Unspecified</pose>\n')
            xml_file.write('        <truncated>0</truncated>\n')
            xml_file.write('        <difficult>0</difficult>\n')
            xml_file.write('        <bndbox>\n')

            center_x = round(float(spt[1].strip()) * width)
            center_y = round(float(spt[2].strip()) * height)
            bbox_width = round(float(spt[3].strip()) * width)
            bbox_height = round(float(spt[4].strip()) * height)
            xmin = str(int(center_x - bbox_width / 2))
            ymin = str(int(center_y - bbox_height / 2))
            xmax = str(int(center_x + bbox_width / 2))
            ymax = str(int(center_y + bbox_height / 2))

            xml_file.write('            <xmin>' + xmin + '</xmin>\n')
            xml_file.write('            <ymin>' + ymin + '</ymin>\n')
            xml_file.write('            <xmax>' + xmax + '</xmax>\n')
            xml_file.write('            <ymax>' + ymax + '</ymax>\n')
            xml_file.write('        </bndbox>\n')
            xml_file.write('    </object>\n')

        xml_file.write('</annotation>')

yolo格式的txt文件转换成 voc的xml格式代码见上图,改路径直接运行(这个参考了Yolo标准数据集格式转Voc数据集_YANJINING-CSDN博客_yolo数据集转voc

  • 8
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
### 回答1: COCO(Common Objects in Context)数据集是一个用于图像识别和物体检测的大型数据集。它包含超过330,000张图像,其中包含超过2,500种物体的注释。此外,COCO数据集还提供了大量用于物体检测和物体关键点标注的图像,是进行目标检测/分割算法研究的重要数据源。 而YOLO(You Only Look Once)模型是一种轻量级的目标检测模型。相比于RCNN和SSD等传统模型,YOLO模型具有速度快、精度高等优点。因此,对于COCO数据集这样大型的数据集,使用YOLO模型进行物体检测是一个极好的选择。 当然,在使用YOLO模型进行目标检测时,需要将COCO数据集转换YOLO格式YOLO格式是一种文本文件格式,每个文件包含许多行。每行代表一个注释框,每一行有五个数字,分别是类别、x、y、w、h。其中,x、y、w、h代表的是目标框中心坐标和宽高。 最后值得一提的是,由于COCO数据集中存在的物体种类较多,为了提高YOLO模型的检测精度,可以加入训练好的预测模型来进行fine-tuning,这样可以大大提升YOLO模型的检测精度。 ### 回答2: COCO数据集是计算机视觉领域中广泛使用的数据集之一。它包含了超过33万张图片,并且其中每张图片都有80个不同的对象标注。COCO数据集可以用于许多计算机视觉任务,例如物体检测、图像分割和姿势估计等。 要在YOLO格式中使用COCO数据集,首先需要将COCO数据集的注释转换YOLO格式所需的注释格式。在COCO数据集中,每个注释都包括了包围框的位置和对应的类别标签。要将这些注释转换YOLO格式所需的注释,需要用相对于图像宽度和高度的坐标来表示包围框的位置。 每个包围框的坐标应该被归一化到0和1之间。对于每个包围框,YOLO格式需要记录下包围框的左上角坐标、宽度和高度。此外,需要根据每个包围框的类别标签为其分配相应的整数编号。建议将哪些类别应该对应哪些整数编号的信息记录在文件中。 转换COCO数据集的注释可能需要一些代码来自动执行这个任务。一些基本的数据处理技能也很有帮助,包括使用Python编程语言、熟悉JSON文件、CSV文件和操作系统命令等。 转换完成后,就可以开始使用YOLO格式的COCO数据集来训练YOLO模型了。使用转换后的注释数据,可以通过训练过程来优化权重和偏置,以便YOLO模型可以检测图像中的物体并将其分类。要验证模型的性能,可以使用交叉验证或者COCO数据集提供的训练和验证数据集。最终,根据测试数据集的性能,可以评估训练出的YOLO模型的性能水平。 ### 回答3: 针对YOLO模型,coco数据集已经提供了训练和测试数据的标注文件,也就是包含物体的类别和其对应的坐标信息。这个标注文件格式YOLO的训练和测试数据格式是一致的。下面给出了coco数据集中标注文件的格式说明: 1. 标注文件的命名规则:   train2017.json – 训练集   val2017.json – 验证集   test2017.json – 测试集 2. 标注文件的基本格式:   {   “info”: info, # 数据集信息   “licenses”: [],   “images”: [image], # 存储所有的图片信息   “annotations”: [anno], # 存储所有图片的标注信息   “categories”: [cat] # 存储所有物体类别信息   } 3. 标注文件中images节点的格式:   {   “id”: int, # 图像的标注id   “file_name”: str, # 图像文件名   “width”: int, # 图像的宽度   “height”: int, # 图像的高度   “date_captured”: datetime,   “license”: int,   “flickr_url”: str,   “coco_url”: str,   “width_original”: int, # 原始图像的宽度   “height_original”: int # 原始图像的高度   } 4. 标注文件中annotations节点的格式:   {   “id”: int, # 标注id   “image_id”: int, # 图像的标注id   “category_id”: int, # 物体类别id   “segmentation”: RLE or [polygon] or [polyline], # 物体的轮廓   “area”: float, # 物体的面积   “bbox”: [x,y,width,height], # 物体的边框坐标信息,x,y表示左上角的坐标,width表示物体的宽度,height表示物体的高度   “iscrowd”: 0 or 1 # 指示该物体是否是一个物体群体   } 5. 标注文件中categories节点的格式:   {   “id”: int, # 物体类别的id   “name”: str, # 物体类别的名称   “supercategory”: str # 物体类别的父类别   } 对于使用YOLO模型进行目标检测,我们可以通过将以上coco数据集的标注文件转换YOLO格式,然后再进行模型的训练和测试。在转换YOLO格式时,需要根据物体的边框坐标信息和图像的大小计算出物体的中心点坐标和宽高比例等信息,以便于模型能够准确地检测出物体的位置和类别。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kkcodeer

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值