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

yolov5中数据集存放格式如下图所示yolov5的数据集格式 :COCO数据集转换成yolov5训练的数据集格式代码

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

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

如上图所示的一个.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的代码中,目标框的标注坐标指的是目标框的中心坐标,所以要进行转换。

以上代码如果有用的话,欢迎拿去!yolov5的数据集格式 :COCO数据集转换成yolov5训练的数据集格式代码

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2022年6月8日
下一篇 2022年6月8日

相关推荐