coco2017数据集百度云下载地址:
百度云下载地址:https://pan.baidu.com/s/1U3pPJ5nDluGdCtYi0njejg
提取码:x3qk



import json
file_path = './instances_val2017.json'
json_info = json.load(open(file_path,'r'))
print(json_info["info"])












安装:
pip install pycocotools==2.0.0
初始化coco实例:
from pycocotools.coco import COCO
val_annotation_file = './instances_val2017.json'
coco = COCO(annotation_file = val_annotation_file)
其中coco变量如下图所示

我们右键选择COCO,“go to”到“Implementation”可以看到COCO类中有以下函数:

COCO.getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None),主要参数是imgIds,传入图片的id,返回这个图像的所有标注信息的index列表。详细的参数如下图所示:

而getAnnIds通常会和loadAnns配合使用,COCO.loadAnns(self, ids=[]),传入annotation index信息,会返回对应标注信息index的标注详细信息。详细的参数列表如下图所示:

注意返回的字典含有一系列信息,其中bbox字段是锚框信息,分别是x,y,w,h,前两者是左上角坐标位置,后两者是锚框宽高,详细形式如下图所示:

COCO.loadImgs(self, ids=[]),传入图片的id,会返回对应id的图片的详细信息,如下图所示:

import os
from pycocotools.coco import COCO
from PIL import Image, ImageDraw
import matplotlib.pyplot as plt
val_annotation_file = "./annotations/instances_val2017.json"
val_img_file = './val2017'
coco = COCO(annotation_file=val_annotation_file)
coco_classes = dict([(v["id"], v["name"]) for k, v in coco.cats.items()])
idx = list(sorted(coco.imgs.keys()))
img_id = idx[0] #排序后最小的图片id为139 ,即img_id=139
ann_idx = coco.getAnnIds(imgIds=img_id)
objects = coco.loadAnns(ann_idx)
#获取图片
##获取图片路径名
path = coco.loadImgs(img_id)[0]["file_name"]
##读取139号图片
img = Image.open(os.path.join(val_img_file, path)).convert('RGB')
#在图片上绘制矩形框
draw = ImageDraw.Draw(img)
##一个图片可能会含有多个锚框,对每一个都进行描绘
for object in objects:
x,y,w,h = object["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[object["category_id"]])
##使用matplotlib绘制
plt.imshow(img)
plt.show()


大类12个,分别为
[‘person’, ‘bicycle’, ‘car’, ‘motorcycle’, ‘airplane’, ‘bus’, ‘train’, ‘truck’, ‘boat’, ‘traffic light’, ‘fire hydrant’, ‘stop sign’, ‘parking meter’, ‘bench’, ‘bird’, ‘cat’, ‘dog’, ‘horse’, ‘sheep’, ‘cow’, ‘elephant’, ‘bear’, ‘zebra’, ‘giraffe’, ‘backpack’, ‘umbrella’, ‘handbag’, ‘tie’, ‘suitcase’, ‘frisbee’, ‘skis’, ‘snowboard’, ‘sports ball’, ‘kite’, ‘baseball bat’, ‘baseball glove’, ‘skateboard’, ‘surfboard’, ‘tennis racket’, ‘bottle’, ‘wine glass’, ‘cup’, ‘fork’, ‘knife’, ‘spoon’, ‘bowl’, ‘banana’, ‘apple’, ‘sandwich’, ‘orange’, ‘broccoli’, ‘carrot’, ‘hot dog’, ‘pizza’, ‘donut’, ‘cake’, ‘chair’, ‘couch’, ‘potted plant’, ‘bed’, ‘dining table’, ‘toilet’, ‘tv’, ‘laptop’, ‘mouse’, ‘remote’, ‘keyboard’, ‘cell phone’, ‘microwave’, ‘oven’, ‘toaster’, ‘sink’, ‘refrigerator’, ‘book’, ‘clock’, ‘vase’, ‘scissors’, ‘teddy bear’, ‘hair drier’, ‘toothbrush’]
大类12个,分别为
[‘appliance’, ‘food’, ‘indoor’, ‘accessory’, ‘electronic’, ‘furniture’, ‘vehicle’, ‘sports’, ‘animal’, ‘kitchen’, ‘person’, ‘outdoor’]
