目标检测|制作MS COCO json格式的数据集

简介

  • MS COCO 是google 开源的大型数据集, 分为目标检测、分割、关键点检测三大任务, 数据集主要由图片和json 标签文件组成。 coco数据集有自带COCO API,方便对json文件进行信息读取。本博客介绍是目标检测数据集格式的制作。

步骤

  • 对现有数据标签文件转化为json格式, json文件主要用字典形式存取, coco原数据集包括:info、licenses、images、annotations、categories 5个关键字,其中每个关键字内容是一个list, list每个元素也是字典。我们制作自己数据集只要3个关键字:images、annotations、categories。images是存放每张图的 名称和ID,annotations存放是每个box 的信息, categories存放是数据集所有类别信息。

代码

  • 下面提供是部分代码段, 主要是参考CenterNet.
    其中det_dict 是原始数据集的所有信息,是一个字典,每个关键字表示图片名称, 关键字对应内容为 label x y w h label1 x1 y1 w1 h1 …
import json
import numpy as np
if __name__ == '__main__':
	pascal_class_name = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", 
  	"car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", 
  	"person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
  
    cat_ids = {cat: i + 1 for i, cat in enumerate(pascal_class_name)}

    cat_info = []
    for i, cat in enumerate(pascal_class_name):
        cat_info.append({'name': cat, 'id': i + 1})
	
	# 主字典
    ret = {'images': [], 'annotations': [], "categories": cat_info}

    cnt = 0
    image_id = 0
    for key in det_dict:
        lines = det_dict[key]
        image_info = {'file_name': key,
                      'id': int(image_id)}
        # images data
        ret['images'].append(image_info)

        # anno data
        for line in lines:
            label = cat_ids[line[0]]
            bbox = np.array(line[1:5], np.float)
            bbox = bbox.astype(np.int).tolist()
            ann = {'image_id': image_id,
                   'id': int(len(ret['annotations']) + 1),
                   'category_id': label,
                   'bbox': bbox,
                   area': bbox[2] * bbox[3],
                   'ignore': 0
                   }
            ret['annotations'].append(ann)
        image_id += 1

    out_path = 'annotations/train.json'
    json.dump(ret, open(out_path, 'w'))

COCO API

  • coco API 常用方法。
	json_file = 'train.json'
	img_root = ‘./’
	coco = coco.COCO(json_file)  # 读取json信息
    images = coco.getImgIds()    # 获取所有图片id
    for img_id in images:
        file_name = coco.loadImgs(ids=[img_id])[0]['file_name']  #  获取一张图片文件名
        img_path = os.path.join(img_root, file_name)                  #  图片绝对路径
        ann_ids =coco.getAnnIds(imgIds=[img_id])                    #  获取这张图片下所有box的id
        anns = coco.loadAnns(ids=ann_ids)								# 获取这张图片下所有box信息	
    
  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值