前段时间自己从COCO官网下载了数据集,但是一直没怎么打开看。但是今天突然想去跑训练的时候才发现,还需要进行格式转换,因为yolo只支持.txt标签方式。然后就是自己从网上查各种转换帖子,但是发现五花八门,错综复杂,都是各种错误,或者写的不清晰,白忙活了一中午,好在最终挑好了,把过程分享出来,希望给刚入门深度学习的小伙伴们避避坑,避免不必要的时间浪费在这上面。

 

官网下载目录如下:

train2017:包含训练所需要的图片

val2017:包含验证训练模型图片

annotations_trainval2017:包含标注json文件

下图是下载下来后其包括的注释文件内容,包括三类文件:

captions:为图像描述的标注文件

instances:为目标检测与实例分割的标注文件

person_keypoints:为人体关键点检测的标注文件

 运行环境,将下面代码cp到pycharm中,修改12,14, 62行,改为自己数据集的位置,运行即可

#COCO 格式的数据集转化为 YOLO 格式的数据集
#--json_path 输入的json文件路径
#--save_path 保存的文件夹名字,默认为当前目录下的labels。

import os
import json
from tqdm import tqdm
import argparse

parser = argparse.ArgumentParser()
#这里根据自己的json文件位置,换成自己的就行
parser.add_argument('--json_path', default='E:/data/COCO2017/annotations_trainval2017/annotations/instances_train2017.json',type=str, help="input: coco format(json)")
#这里设置.txt文件保存位置
parser.add_argument('--save_path', default='E:/data/COCO', type=str, help="specify where to save the output dir of labels")
arg = parser.parse_args()

def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = box[0] + box[2] / 2.0
    y = box[1] + box[3] / 2.0
    w = box[2]
    h = box[3]
#round函数确定(xmin, ymin, xmax, ymax)的小数位数
    x = round(x * dw, 6)
    w = round(w * dw, 6)
    y = round(y * dh, 6)
    h = round(h * dh, 6)
    return (x, y, w, h)

if __name__ == '__main__':
    json_file =   arg.json_path # COCO Object Instance 类型的标注
    ana_txt_save_path = arg.save_path  # 保存的路径

    data = json.load(open(json_file, 'r'))
    if not os.path.exists(ana_txt_save_path):
        os.makedirs(ana_txt_save_path)

    id_map = {} # coco数据集的id不连续!重新映射一下再输出!
    with open(os.path.join(ana_txt_save_path, 'classes.txt'), 'w') as f:
        # 写入classes.txt
        for i, category in enumerate(data['categories']):
            f.write(f"{category['name']}\n")
            id_map[category['id']] = i
    # print(id_map)
    #这里需要根据自己的需要,更改写入图像相对路径的文件位置。
    list_file = open(os.path.join(ana_txt_save_path, 'train2017.txt'), 'w')
    for img in tqdm(data['images']):
        filename = img["file_name"]
        img_width = img["width"]
        img_height = img["height"]
        img_id = img["id"]
        head, tail = os.path.splitext(filename)
        ana_txt_name = head + ".txt"  # 对应的txt名字,与jpg一致
        f_txt = open(os.path.join(ana_txt_save_path, ana_txt_name), 'w')
        for ann in data['annotations']:
            if ann['image_id'] == img_id:
                box = convert((img_width, img_height), ann["bbox"])
                f_txt.write("%s %s %s %s %s\n" % (id_map[ann["category_id"]], box[0], box[1], box[2], box[3]))
        f_txt.close()
        #将图片的相对路径写入train2017或val2017的路径
        list_file.write('E:/data/COCO2017/train2017/%s.jpg\n' %(head))
    list_file.close()

最后我们会在自己设置好的目录中得到与图片对应的.txt文件,然后再把目录进行转换为yolo的目录格式即可训练

转换来说相对耗时,现把我已经整理好的COCO2017标准数据集(YOLO .txt)分享出来

无法分享~~~太大了

如果有疑问可以评论,看到我会回复。 

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐