MicrosoftのCommon Objects in Contextデータセット(通称MS COCO dataset)は、Microsoft が提供しているアノテーション付きの画像のデータセットで、MS COCO datasetに対して、MSCOCO APIを使ってアクセスします。
MS COCO datasetのダウンロード
「MS COCO dataset」は、次のようにしてデータをダウンロードします。
wget -q http://images.cocodataset.org/zips/train2017.zip wget -q http://images.cocodataset.org/zips/val2017.zip wget -q http://images.cocodataset.org/annotations/annotations_trainval2017.zip unzip train2017.zip val2017.zip annotations_trainval2017.zip
ダウンロードして解凍すると、以下のフォルダ構造になります。
F:\MSCOCO
├─annotations
│ captions_train2017.json
│ captions_val2017.json
│ instances_train2017.json
│ instances_val2017.json
│ person_keypoints_train2017.json
│ person_keypoints_val2017.json
│
├─train2017
│ 000000000009.jpg
│ 000000000025.jpg
│ 000000000030.jpg
│ 000000000034.jpg
│ ・・・
│ 000000581921.jpg
│ 000000581929.jpg
│
└─val2017
000000000139.jpg
000000000285.jpg
000000000632.jpg
000000000724.jpg
・・・
MSCOCO API のインストール
MSCOCO API のPythonライブラリを次のようにインストールします。
# pycocotools のビルドに Cython が必要 pip install cython pip install pycocotools
MSCOCO API を使ったMS COCO datasetアクセススクリプトの作成
MS COCO datasetアクセススクリプト「MsCocoAccess.py」を作成します。MS COCO datasetのカテゴリ を「banana」にしてデータセットを取得しました。
- 43-73行目で画像を指定して、その画像に関するアノテーション情報を取得して、画像に重ねて表示します。
- 77-108行目で画像を指定して、その画像に関するアノテーション情報を取得して、アノテーション情報からbboxとcategoryを取得して、画像に重ねて表示します。77-85行目では、フォルダに保存されている画像をインデックス化し、85行目で1回だけルールさせているだけで、インデックス化した情報は使用していません。
MsCocoAccess.py
import os
from pathlib import Path
from pycocotools.coco import COCO
from PIL import Image, ImageDraw
import matplotlib.pyplot as plt
json_path = "F:\\MSCOCO\\annotations\\instances_val2017.json"
img_path = "F:\\MSCOCO\\val2017"
# load coco data
coco = COCO(annotation_file=json_path)
print("\n************1**********\n");
# 指定したカテゴリに対応するカテゴリ ID を取得する。
print(coco.getCatIds(catNms=["banana"]))
# 指定した上位カテゴリに属するカテゴリ ID を取得する。
print(coco.getCatIds(supNms=["food"]))
print("\n***********2***********\n");
# カテゴリ ID の一覧を取得する。
cat_ids = coco.getCatIds(catNms=["banana"])
# 指定したカテゴリ ID の物体がすべて存在する画像の ID 一覧を取得する。
img_ids = coco.getImgIds(catIds=cat_ids)
print(img_ids)
print("\n***********3***********\n");
# 指定した画像 ID の情報を取得する。
imgs = coco.loadImgs(577539)
from pprint import pprint
pprint(imgs)
print("\n***********4***********\n");
# 指定した 画像 ID に対応するアノテーション ID を取得する。
anno_ids = coco.getAnnIds(269314)
print(anno_ids)
print("\n***********5**********\n");
# 指定した 画像 ID に対応するアノテーション ID を取得する。
anno_ids = coco.getAnnIds(577539)
print(anno_ids)
annos = coco.loadAnns(anno_ids[2])
from pprint import pprint
pprint(annos)
img_id = 577539
# 指定した画像 ID に対応する画像の情報を取得する。
img_info, = coco.loadImgs(img_id)
img_path = Path("F:\\MSCOCO\\val2017") / img_info["file_name"]
print(img_path)
# 指定した 画像 ID に対応するアノテーション ID を取得する。
anno_ids = coco.getAnnIds(img_id)
# 指定したアノテーション ID に対応するアノテーションの情報を取得する。
annos = coco.loadAnns(anno_ids)
# 画像を読み込む。
img = plt.imread(img_path)
# 画像を描画する。
plt.imshow(img)
# アノテーション結果を描画する。
coco.showAnns(annos)
plt.show()
print("\n***********6***********\n");
# get all image index info
ids = list(sorted(coco.imgs.keys()))
print("number of images: {}".format(len(ids)))
# get all coco class labels
coco_classes = dict([(v["id"], v["name"]) for k, v in coco.cats.items()])
# Traverse the first three images
for img_id in ids[:1]:
# Obtain the corresponding image id All of the annotations idx Information
ann_ids = coco.getAnnIds(577539)
# according to annotations idx Information get all annotation information
targets = coco.loadAnns(ann_ids)
# get image file name
path = coco.loadImgs(img_id)[0]['file_name']
print("image file name: {}".format(path))
# read image
img = Image.open(os.path.join(img_path)).convert('RGB')
draw = ImageDraw.Draw(img)
# draw box to image
for target in targets:
x, y, w, h = target["bbox"]
x1, y1, x2, y2 = x, y, int(x + w), int(y + h)
draw.rectangle((x1, y1, x2, y2))
draw.text((x1, y1), coco_classes[target["category_id"]])
# show image
plt.imshow(img)
plt.show()
MSCOCO API を使ったMS COCO datasetアクセススクリプトの実行
作成したMS COCO datasetアクセススクリプト「MsCocoAccess.py」を実行すると、次のメッセージを出力します。
G:\Python38\python.exe F:/MSCOCO/MsCocoAccess.py
loading annotations into memory...
Done (t=0.67s)
creating index...
index created!
************1**********
[52]
[52, 53, 54, 55, 56, 57, 58, 59, 60, 61]
***********2***********
[269314, 577539, 575500, 480275, 407574, 40471, 331799, 2587, 161820, 348708, 457262, 453708, 3661, 356428, 346707, 312406, 271471, 163951, 459887, 78959, 560256, 28809, 8844, 128658, 378515, 219283, 581781, 189078, 66706, 548506, 119452, 236721, 389812, 527029, 272566, 66231, 114871, 246968, 509131, 13004, 59598, 491216, 535253, 479448, 279769, 313562, 429281, 474854, 465129, 69356, 112378, 63740, 425226, 90891, 371472, 191761, 147740, 79651, 349480, 17714, 550714, 290619, 521540, 571718, 58705, 499031, 489305, 139099, 192871, 352618, 227187, 480122, 12667, 6012, 190853, 193926, 465806, 322959, 37777, 466835, 530836, 298396, 441247, 482719, 293794, 113589, 468925, 326082, 158660, 185802, 294350, 173008, 437205, 415194, 74209, 575970, 50149, 165351, 188906, 125936, 376307, 439290, 139260]
***********3***********
[{'coco_url': 'http://images.cocodataset.org/val2017/000000577539.jpg',
'date_captured': '2013-11-19 21:39:18',
'file_name': '000000577539.jpg',
'flickr_url': 'http://farm4.staticflickr.com/3494/3850219428_10c4b01c88_z.jpg',
'height': 334,
'id': 577539,
'license': 4,
'width': 500}]
***********4***********
[51951, 1042088]
***********5**********
[718033, 1696885, 1904146, 1904550, 2160325]
[{'area': 2222.2498000000005,
'bbox': [249.85, 181.31, 78.94, 45.12],
'category_id': 52,
'id': 1904146,
'image_id': 577539,
'iscrowd': 0,
'segmentation': [[271.54,
181.31,
267.2,
196.93,
255.92,
203.0,
249.85,
214.28,
255.92,
226.43,
328.79,
222.09,
317.52,
190.86,
307.97,
200.4,
276.74,
182.18]]}]
F:\MSCOCO\val2017\000000577539.jpg
***********6***********
number of images: 5000
image file name: 000000000139.jpg
Process finished with exit code 0
指定した 画像 ID「577539」 に対応するアノテーション情報すべてをshowAnns関数で可視化します。
指定した 画像 ID「577539」に対応するbboxとcategoryを視覚化します。
COCO dataset カテゴリ一覧
91種類あるCOCO dataset カテゴリを次に示します。
| id | supercategory | name |
|---|---|---|
| 1 | person | person |
| 2 | vehicle | bicycle |
| 3 | vehicle | car |
| 4 | vehicle | motorcycle |
| 5 | vehicle | airplane |
| 6 | vehicle | bus |
| 7 | vehicle | train |
| 8 | vehicle | truck |
| 9 | vehicle | boat |
| 10 | outdoor | traffic light |
| 11 | outdoor | fire hydrant |
| 12 | outdoor | street sign* |
| 13 | outdoor | stop sign |
| 14 | outdoor | parking meter |
| 15 | outdoor | bench |
| 16 | animal | bird |
| 17 | animal | cat |
| 18 | animal | dog |
| 19 | animal | horse |
| 20 | animal | sheep |
| 21 | animal | cow |
| 22 | animal | elephant |
| 23 | animal | bear |
| 24 | animal | zebra |
| 25 | animal | giraffe |
| 26 | animal | hat* |
| 27 | accessory | backpack |
| 28 | accessory | umbrella |
| 29 | accessory | shoe* |
| 30 | accessory | eye glasses* |
| 31 | accessory | handbag |
| 32 | accessory | tie |
| 33 | accessory | suitcase |
| 34 | sports | frisbee |
| 35 | sports | skis |
| 36 | sports | snowboard |
| 37 | sports | sports ball |
| 38 | sports | kite |
| 39 | sports | baseball bat |
| 40 | sports | baseball glove |
| 41 | sports | skateboard |
| 42 | sports | surfboard |
| 43 | sports | tennis racket |
| 44 | kitchen | bottle |
| 45 | kitchen | plate* |
| 46 | kitchen | wine glass |
| 47 | kitchen | cup |
| 48 | kitchen | fork |
| 49 | kitchen | knife |
| 50 | kitchen | spoon |
| 51 | kitchen | bowl |
| 52 | food | banana |
| 53 | food | apple |
| 54 | food | sandwich |
| 55 | food | orange |
| 56 | food | broccoli |
| 57 | food | carrot |
| 58 | food | hot dog |
| 59 | food | pizza |
| 60 | food | donut |
| 61 | food | cake |
| 62 | furniture | chair |
| 63 | furniture | couch |
| 64 | furniture | potted plant |
| 65 | furniture | bed |
| 66 | furniture | mirror* |
| 67 | furniture | dining table |
| 68 | furniture | window* |
| 69 | furniture | desk* |
| 70 | furniture | toilet |
| 71 | furniture | door* |
| 72 | electronic | tv |
| 73 | electronic | laptop |
| 74 | electronic | mouse |
| 75 | electronic | remote |
| 76 | electronic | keyboard |
| 77 | electronic | cell phone |
| 78 | appliance | microwave |
| 79 | appliance | oven |
| 80 | appliance | toaster |
| 81 | appliance | sink |
| 82 | appliance | refrigerator |
| 83 | appliance | blender* |
| 84 | indoor | book |
| 85 | indoor | clock |
| 86 | indoor | vase |
| 87 | indoor | scissors |
| 88 | indoor | teddy bear |
| 89 | indoor | hair drier |
| 90 | indoor | toothbrush |
| 91 | indoor | hair brush* |

