简介
- 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
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信息