【筆記】製作自己的MSCOCO數據集

推薦先從這裏學習從零開始製作自己的Pascal VOC數據集


1 MSCOCO數據集簡介

1.1 概要

現今最流行的公開數據集是啥?COCO,Common Objects in Context。現如今最先進的視覺檢測模型都是在COCO上評測了。
相較於上一代的Pascal VOC,COCO擁有更多的圖片–330K,更多的標註–1.5 million,更多的物體類別–80類,更復雜的場景,更多的小的物體,總之就是更大更復雜更具挑戰性,也更具說服力。想了解更多,移步COCO官網

1.2 數據集格式

COCO一共有5種不同任務分類,分別是目標檢測、關鍵點檢測、語義分割、場景分割和圖像描述。COCO數據集的標註文件以JSON格式保存,官方的註釋文件有仨 captions_type.json instances_type.json person_keypoints_type.json,其中的type是 train/val/test+year,比如captions_train2017.json instances_train2017.json person_keypoints_train2017.json,其中目標檢測的註釋放在instances_xxx.json裏。

公共格式

{
    //公共格式,三個json文件開頭都是他們
    "info" : info,  //數據集的信息,
    "images" : [image],//數據集中所有圖片的信息,詳細見下方
    "annotations" : [annotation], //數據集中註釋的信息
    "licenses" : [license],//這個是證書信息,跑模型時不用理會
}

info{
    "year" : int, //數據集年份 2014,2015,2017。
    "version" : str, //剩下信息不必理會
    "description" : str, 
    "contributor" : str, 
    "url" : str, 
    "date_created" : datetime,
}

image{//對每一張圖片
    "id" : int, //可唯一標識圖片的  圖片id
    "width" : int,//圖片的 寬、高,,,,沒有提到圖片的depth
    "height" : int,
    "file_name" : str, //文件名稱 ,"xxx.jpg"
    "license" : int, 
    "flickr_url" : str,
    "coco_url" : str, 
    "date_captured" : datetime,
}

license{
    "id" : int, 
    "name" : str,
    "url" : str,
}

特有格式-目標檢測類

//注意:COCO中的每個annotation是獨立的,有自己的id。比如說目標檢測,一張圖片中的每個object是單獨存在的,都有自己的一個annotation實例。
annotation{
    "id" : int, //object id
    "image_id" : int,//這個object在哪個圖片中
    "category_id" : int, //object的類別
    "segmentation" : RLE or [polygon],//分割用, 
	"area" : float,
	"bbox" : [x,y,width,height],//劃重點,bbox,以左上角爲原點,是實際座標!!
	"iscrowd" : 0 or 1,
}
categories[//這個是所有類別的一個總的集合,python.list,比如COCO一共有80類,那它的大小就是80。其中的每一個類別又有如下的結構
    {
        "id" : int,//類別id
        "name" : str, //類名
        "supercategory" : str,//父 類名,通常不用管
    }
]

2 動手製作

僅以目標檢測爲例!!!
自己製作時只需要image,annotation,categories就足夠了。

2.1 數據集框架準備

找個位置,新建文件夾coco,進入coco,新建兩個文件夾images,annotations,最終形成的目錄結構應該是

  • coco/
    • images/
    • annotations/

2.1 製作xml格式的annotation文件

參考【筆記】從零開始製作自己的Pascal VOC數據集2.1小節。

2.2 xml2coco

把剛纔用到的圖片直接拷貝到 coco/images
運行如下腳本:
注意:腳本文件來自腳本地址,只做了一點修改使得結果更符合強迫症患者

# -*- coding: utf-8 -*-
# @Time    : 2019/7/8 16:10
# @Author  : lazerliu
# @File    : voc2coco.py
# just for object detection
import xml.etree.ElementTree as ET
import os
import json

coco = dict()
coco['images'] = []
coco['type'] = 'instances'
coco['annotations'] = []
coco['categories'] = []

category_set = dict()
image_set = set()

category_item_id = 0
image_id = 0
annotation_id = 0


def addCatItem(name):
    global category_item_id
    category_item = dict()
    category_item['supercategory'] = 'none'
    category_item_id += 1
    category_item['id'] = category_item_id
    category_item['name'] = name
    coco['categories'].append(category_item)
    category_set[name] = category_item_id
    return category_item_id


def addImgItem(file_name, size):
    global image_id
    if file_name is None:
        raise Exception('Could not find filename tag in xml file.')
    if size['width'] is None:
        raise Exception('Could not find width tag in xml file.')
    if size['height'] is None:
        raise Exception('Could not find height tag in xml file.')
    img_id = "%04d" % image_id
    image_id += 1
    image_item = dict()
    image_item['id'] = int(img_id)
    # image_item['id'] = image_id
    image_item['file_name'] = file_name
    image_item['width'] = size['width']
    image_item['height'] = size['height']
    coco['images'].append(image_item)
    image_set.add(file_name)
    return image_id


def addAnnoItem(object_name, image_id, category_id, bbox):
    global annotation_id
    annotation_item = dict()
    annotation_item['segmentation'] = []
    seg = []
    # bbox[] is x,y,w,h
    # left_top
    seg.append(bbox[0])
    seg.append(bbox[1])
    # left_bottom
    seg.append(bbox[0])
    seg.append(bbox[1] + bbox[3])
    # right_bottom
    seg.append(bbox[0] + bbox[2])
    seg.append(bbox[1] + bbox[3])
    # right_top
    seg.append(bbox[0] + bbox[2])
    seg.append(bbox[1])

    annotation_item['segmentation'].append(seg)

    annotation_item['area'] = bbox[2] * bbox[3]
    annotation_item['iscrowd'] = 0
    annotation_item['ignore'] = 0
    annotation_item['image_id'] = image_id
    annotation_item['bbox'] = bbox
    annotation_item['category_id'] = category_id
    annotation_id += 1
    annotation_item['id'] = annotation_id
    coco['annotations'].append(annotation_item)


def parseXmlFiles(xml_path):
    for f in os.listdir(xml_path):
        if not f.endswith('.xml'):
            continue

        bndbox = dict()
        size = dict()
        current_image_id = None
        current_category_id = None
        file_name = None
        size['width'] = None
        size['height'] = None
        size['depth'] = None

        xml_file = os.path.join(xml_path, f)
        # print(xml_file)

        tree = ET.parse(xml_file)
        root = tree.getroot()
        if root.tag != 'annotation':
            raise Exception('pascal voc xml root element should be annotation, rather than {}'.format(root.tag))

        # elem is <folder>, <filename>, <size>, <object>
        for elem in root:
            current_parent = elem.tag
            current_sub = None
            object_name = None

            if elem.tag == 'folder':
                continue

            if elem.tag == 'filename':
                file_name = elem.text
                if file_name in category_set:
                    raise Exception('file_name duplicated')

            # add img item only after parse <size> tag
            elif current_image_id is None and file_name is not None and size['width'] is not None:
                if file_name not in image_set:
                    current_image_id = addImgItem(file_name, size)
                    # print('add image with {} and {}'.format(file_name, size))
                else:
                    raise Exception('duplicated image: {}'.format(file_name))
                    # subelem is <width>, <height>, <depth>, <name>, <bndbox>
            for subelem in elem:
                bndbox['xmin'] = None
                bndbox['xmax'] = None
                bndbox['ymin'] = None
                bndbox['ymax'] = None

                current_sub = subelem.tag
                if current_parent == 'object' and subelem.tag == 'name':
                    object_name = subelem.text
                    if object_name not in category_set:
                        current_category_id = addCatItem(object_name)
                    else:
                        current_category_id = category_set[object_name]

                elif current_parent == 'size':
                    if size[subelem.tag] is not None:
                        raise Exception('xml structure broken at size tag.')
                    size[subelem.tag] = int(subelem.text)

                # option is <xmin>, <ymin>, <xmax>, <ymax>, when subelem is <bndbox>
                for option in subelem:
                    if current_sub == 'bndbox':
                        if bndbox[option.tag] is not None:
                            raise Exception('xml structure corrupted at bndbox tag.')
                        bndbox[option.tag] = int(option.text)

                # only after parse the <object> tag
                if bndbox['xmin'] is not None:
                    if object_name is None:
                        raise Exception('xml structure broken at bndbox tag')
                    if current_image_id is None:
                        raise Exception('xml structure broken at bndbox tag')
                    if current_category_id is None:
                        raise Exception('xml structure broken at bndbox tag')
                    bbox = []
                    # x
                    bbox.append(bndbox['xmin'])
                    # y
                    bbox.append(bndbox['ymin'])
                    # w
                    bbox.append(bndbox['xmax'] - bndbox['xmin'])
                    # h
                    bbox.append(bndbox['ymax'] - bndbox['ymin'])
                    # print('add annotation with {},{},{},{}'.format(object_name, current_image_id, current_category_id,
                    #                                                bbox))
                    addAnnoItem(object_name, current_image_id, current_category_id, bbox)


if __name__ == '__main__':
	#修改這裏的兩個地址,一個是xml文件的父目錄;一個是生成的json文件的絕對路徑
    xml_path = 'xxx/VOCdevkit/VOC2007/Annotations/'
    json_file = 'xxx/coco/annotations/instances.json'
    parseXmlFiles(xml_path)
    json.dump(coco, open(json_file, 'w'))

至此,自制的coco數據集完成。

3 測試

測試製作的coco數據集能否被cocoapi識別。

3.1 安裝cocoapi

git clone https://github.com/cocodataset/cocoapi.git
cd cocoapi/PythonAPI
make

3.2 實測

# -*- coding: utf-8 -*-
# @Time    : 2019/7/8 14:32
# @Author  : lazerliu
# @File    : CocoForm_Learn.py
import sys
import json

sys.path.append("/xxx/cocoapi/PythonAPI")#把cocoapi的絕對路徑加上
from pycocotools.coco import COCO

ann_file = "xxx/coco/annotations/instances.json"# json文件的絕對路徑
coco = COCO(annotation_file=ann_file)

print("coco\nimages.size [%05d]\tannotations.size [%05d]\t category.size [%05d]\ndone!"
      %(len(coco.imgs),len(coco.anns),len(coco.cats)))

在這裏插入圖片描述

【完】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章