yolov5的数据集格式 :COCO数据集转换成yolov5训练的数据集格式代码

yolov5中数据集存放格式如下图所示

其labels文件夹下,存放的为.txt文件,每个txt名称对应images文件夹下的图片名称,txt中的内容为

如上图所示的一个.txt文件所示,一共有四行,每行对应一个目标框,该txt对应的图片有四个目标框,每行的数值分别对应category_id、归一化的目标框中心坐标x、y,和归一化的目标框w、h。归一化的含义即原来的数值分别除以对应的图片的wide和high。下面的代码可以直接将原先coco数据格式中annotations下json标注文件读取,并生成对应图片的.txt标注文件,保存在./fewshotlogodetection_round1_train_202204/train/annotations文件夹下,以便于用yolov5进行训练

import json

with open('./fewshotlogodetection_round1_train_202204/train/annotations/instances_train2017.json') as f:
    Json = json.load(f)
    annotations = Json['annotations']
    images = Json['images']
    image_id_name_dict = {}
    image_id_width_dict = {}
    image_id_height_dict = {}
    for image in images:
        image_id_name_dict[image['id']] = image['file_name']
        image_id_height_dict[image['id']] = image['height']
        image_id_width_dict[image['id']] = image['width']
    # print(image_id_name_dict)
    for i in range(2476):
        for annotation in annotations:
            if annotation['image_id'] != i:  # i表示第i张照片,数据集共2476张
                continue
            bbox = annotation['bbox']
            x, y, w, h = bbox
            x = x + w / 2
            y = y + h / 2
            width = image_id_width_dict[i]
            height = image_id_height_dict[i]
            x = str(x / width)
            y = str(y / height)
            w = str(w / width)
            h = str(h / height)
            with open('./fewshotlogodetection_round1_train_202204/train/annotations/{}.txt'.format(
                    image_id_name_dict[i].split('.')[0]), 'a') as f:
                annotation['category_id']=annotation['category_id']-1
                category=str(annotation['category_id'])
                print(category)
                f.write(category+' '+x+' '+y+' '+w+' '+h+'\n')

其中用到了公式x=x+w/2,y=y+h/2,原因是在coco格式下标注的目标框位置x、y代表的是目标框左上角的位置坐标,而在yolov5的代码中,目标框的标注坐标指的是目标框的中心坐标,所以要进行转换。

以上代码如果有用的话,欢迎拿去!

  • 8
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值