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