代码实现如何将yolov5数据格式转换为coco格式

这篇具有很好参考价值的文章主要介绍了代码实现如何将yolov5数据格式转换为coco格式。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

很多训练算法使用coco格式,而原版的数据集可能采用yolov5的数据格式,故写个简单的教程;

yolov5数据集的目录格式:

yolo转coco,计算机视觉,基础算法,python,人工智能,深度学习,计算机视觉 images存放的图像,例如 1.jpg,2.jpg.

labels存放的是对应图片的标注信息,例如 1.txt,2.txt.

txt 中信息是这样的:

yolo转coco,计算机视觉,基础算法,python,人工智能,深度学习,计算机视觉

(框高)每一行对应一个bbox框信息,分别是class_id ,xc(框的中心x坐标),yc(框的中心x坐标),w(框宽),h (框高)

coco数据集的目录如下:

yolo转coco,计算机视觉,基础算法,python,人工智能,深度学习,计算机视觉

instances_test2017.json的格式如下:

 


#COCO总体结构如下
{
  "info": info,
  "licenses": [license],
  "categories": [categories],
  "images": [image],
  "annotations": [annotation],
}

#其中info,license,categories,image,annotation 的说明如下-----

info = {
    "year": int,               #年份
    "version": str,            #数据集版本
    "description": str,        #数据集描述
    "contributor": str,        #数据集的提供者
    "url": str,                #数据集的下载地址
    "date_created": datetime,  #数据集的创建日期
}

categories ={
    "id": int, #类别id
    "name": str,#类别名称
    "supercategory": str,##大类名
 }

license = {
    "id": int,
    "name": str,
    "url": str,
}
image = {
    "id": int, #图像的索引id,自己指定
    "width": int,#图像的宽
    "height": int,#图像的高
    "file_name": str,#图像的文件名
    "license": int,
    "flickr_url": str,
    "coco_url": str,
    "date_captured": datetime,
}
annotation = {
    "id": int, #boudingbox的索引id,自己指定
    "image_id": int,#对应所在图像的索引id;
    "category_id": int,#所属类别的id;
    "segmentation": RLE or [polygon],#分割的点集序列;
    "area": float,#bbox的面积
    "bbox": [x,y,width,height],#重要,左上角点的坐标,bbox的宽高;
    "iscrowd": 0 or 1, ##是否拥挤
# }

完成的转换代码如下:文章来源地址https://www.toymoban.com/news/detail-655932.html

import json
import os
import shutil

import cv2

# info ,license,categories 结构初始化;
# 在train.json,val.json,test.json里面信息是一致的;

# info,license暂时用不到
info = {
    "year": 2022,
    "version": '1.0',
    "date_created": 2022 - 10 - 15
}

licenses = {
    "id": 1,
    "name": "null",
    "url": "null",
}

#自己的标签类别,跟yolov5的要对应好;
categories = [
    {
        "id": 0,
        "name": 'class_1',
        "supercategory": 'lines',
    },
    {
        "id": 1,
        "name": 'class_2',
        "supercategory": 'lines',
    }
]

#初始化train,test数据字典
# info licenses categories 在train和test里面都是一致的;
train_data = {'info': info, 'licenses': licenses, 'categories': categories, 'images': [], 'annotations': []}
test_data = {'info': info, 'licenses': licenses, 'categories': categories, 'images': [], 'annotations': []}

# image_path 对应yolov5的图像路径,比如images/train;
# label_path 对应yolov5的label路径,比如labels/train 跟images要对应;
def v5_covert_coco_format(image_path, label_path):
    images = []
    annotations = []
    for index, img_file in enumerate(os.listdir(image_path)):
        if img_file.endswith('.jpg'):
            image_info = {}
            img = cv2.imread(os.path.join(image_path, img_file))
            height, width, channel = img.shape
            image_info['id'] = index
            image_info['file_name'] = img_file
            image_info['width'], image_info['height'] = width, height
        else:
            continue
        if image_info != {}:
            images.append(image_info)
        # 处理label信息-------
        label_file = os.path.join(label_path, img_file.replace('.jpg', '.txt'))
        with open(label_file, 'r') as f:
            for idx, line in enumerate(f.readlines()):
                info_annotation = {}
                class_num, xs, ys, ws, hs = line.strip().split(' ')
                class_id, xc, yc, w, h = int(class_num), float(xs), float(ys), float(ws), float(hs)
                xmin = (xc - w / 2) * width
                ymin = (yc - h / 2) * height
                xmax = (xc + w / 2) * width
                ymax = (yc + h / 2) * height
                bbox_w = int(width * w)
                bbox_h = int(height * h)
                img_copy = img[int(ymin):int(ymax),int(xmin):int(xmax)].copy()

                info_annotation["category_id"] = class_id  # 类别的id
                info_annotation['bbox'] = [xmin, ymin, bbox_w, bbox_h]  ## bbox的坐标
                info_annotation['area'] = bbox_h * bbox_w ###area
                info_annotation['image_id'] = index # bbox的id
                info_annotation['id'] = index * 100 + idx  # bbox的id
                # cv2.imwrite(f"./temp/{info_annotation['id']}.jpg", img_copy)
                info_annotation['segmentation'] = [[xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax]]  # 四个点的坐标
                info_annotation['iscrowd'] = 0  # 单例
                annotations.append(info_annotation)
    return images, annotations

# key == train,test,val
# 对应要生成的json文件,比如instances_train2017.json,instances_test2017.json,instances_val2017.json
# 只是为了不重复写代码。。。。。
def gen_json_file(yolov5_data_path, coco_format_path, key):
    # json path
    json_path = os.path.join(coco_format_path, f'annotations/instances_{key}2017.json')
    dst_path = os.path.join(coco_format_path, f'{key}2017')
    if not os.path.exists(os.path.dirname(json_path)):
        os.makedirs(os.path.dirname(json_path), exist_ok=True)
    data_path = os.path.join(yolov5_data_path, f'images/{key}')
    label_path = os.path.join(yolov5_data_path, f'labels/{key}')
    images, anns = v5_covert_coco_format(data_path, label_path)
    if key == 'train':
        train_data['images'] = images
        train_data['annotations'] = anns
        with open(json_path, 'w') as f:
            json.dump(train_data, f, indent=2)
        # shutil.copy(data_path,'')
    elif key == 'test':
        test_data['images'] = images
        test_data['annotations'] = anns
        with open(json_path, 'w') as f:
            json.dump(test_data, f, indent=2)
    else:
        print(f'key is {key}')
    print(f'generate {key} json success!')
    return

if __name__ == '__main__':

    yolov5_data_path = '/your/yolov5/datasets/path'
    coco_format_path = '/your/coco/datasets/path'
    gen_json_file(yolov5_data_path, coco_format_path,key='train')
    gen_json_file(yolov5_data_path, coco_format_path,key='test')

到了这里,关于代码实现如何将yolov5数据格式转换为coco格式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Python将COCO格式实例分割数据集转换为YOLO格式实例分割数据集

    由于本人水平有限,难免出现错漏,敬请批评改正。 更多精彩内容,可点击进入YOLO系列专栏或我的个人主页查看 YOLOv5:添加SE、CBAM、CoordAtt、ECA注意力机制 YOLOv5:yolov5s.yaml配置文件解读、增加小目标检测层 YOLOv5:IoU、GIoU、DIoU、CIoU、EIoU YOLOv7训练自己的数据集(口罩检测)

    2024年02月15日
    浏览(23)
  • 数据集格式相互转换——CoCo、VOC、YOLO、TT100K

    将annotations目录下的所有xml标注文件按coco格式写入了json文件中。 此处得到的是全部的标签信息,可根据如下代码进行train、val和test的比例划分: train和val同理。 train、val和test分别执行一次即可。 以上代码参考自博文数据转换。

    2023年04月09日
    浏览(28)
  • YOLOv5的Tricks | 【Trick15】使用COCO API评估模型在自己数据集的结果

    如有错误,恳请指出。 在解析yolov5整个工程项目的时候要,已经对其detect.py脚本和val.py脚本进行分别的解析。其中,个人觉得detect脚本写得过于冗杂,所以分别为每个任务(图片推理,视频推理,摄像头推理)单独的写了个简单易懂的推理脚本。 在之前在解析完val.py脚本之

    2024年02月07日
    浏览(33)
  • segmentation后 mask图片数据转换成coco对应的json格式

    segmentation后 mask二值图片数据转换成coco对应的json格式 转出来之后的json数据中segmentation部分会有一些问题,它不是一个1 * n维度的数据 而是包含了很多段,需要合并 如图: 合并之前: 合并之后,所有的边缘点在一个list中: 最终转好的格式如下图: 合并代码:

    2024年02月12日
    浏览(26)
  • 使用LabelMe标注目标检测数据集并转换为COCO2017格式

    当你安装好labelme启动后,open dir开始标注,选择Create Rectangle 拖拽画框,然后选择类别(没有就直接输入会自动新建),标注好一幅图后点击next image会弹框提示保存json文件,保存即可。 当你将所有图像标注完后,点击Next Image是没有反应的(因为没有Next图了),此时直接x掉

    2024年02月11日
    浏览(29)
  • 【YOLOV5-6.x讲解】数据增强方式介绍+代码实现

    【YOLOV5-6.x 版本讲解】整体项目代码注释导航 现在YOLOV5已经更新到6.X版本,现在网上很多还停留在5.X的源码注释上,因此特开一贴传承开源精神!5.X版本的可以看其他大佬的帖子本文章主要从6.X版本出发,主要解决6.X版本的项目注释与代码分析!...... https://blog.csdn.net/qq_3923

    2023年04月09日
    浏览(25)
  • YOLOv8 OBB实现自有数据集缺陷旋转检测,从数据标记格式转换到训练的手把手教程

    💡💡💡 本文内容:YOLOv8 OBB实现自有数据集缺陷旋转检测,从数据标记到训练的手把手教程 YOLO OBB格式通过四个角点指定边界框,坐标在0到1之间归一化。它遵循以下格式: 在内部,YOLO以xywhr格式处理损失和输出,xywhr格式表示边界框的中心点(xy)、宽度、高度和旋转。   直接

    2024年01月16日
    浏览(47)
  • [yolov5] yolo的数据标签格式

    yolov5 的标签格式 https://github.com/ultralytics/yolov5/issues/9816 你好!。感谢您询问YOLOv5🚀数据集格式。用于分割的XY坐标与用于长方体中心的标准坐标相同。 为了正确训练,您的数据必须为YOLOv5格式。有关数据集设置的完整文档以及开始培训您的第一个模型所需的所有步骤,请参阅

    2024年02月04日
    浏览(37)
  • VOC/YOLO/COCO数据集格式转换及LabelImg/Labelme/精灵标注助手Colabeler标注工具介绍

    数据集格式:VOC(xml)、YOLO(txt)、COCO(json) 本文主要对 Label格式 ,以及 LabelImg、Labelme、精灵标注助手Colabeler 这常用的三种数据标注软件进行介绍。 LabelImg是目标检测数据标注工具,可以标注标注两种格式: VOC标签格式,标注的标签存储在xml文件 YOLO标签格式,标注的标签存储在

    2023年04月22日
    浏览(74)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包