MS COCO数据集介绍以及pycocotools简单使用

2023-10-25 20:30

本文主要是介绍MS COCO数据集介绍以及pycocotools简单使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • 1. MS COCO数据集简介
    • 2. MS COCO数据集下载
    • 3. MS COCO标注文件格式
      • 3.1 使用Python的json库查看
      • 3.2 使用官方cocoAPI查看
        • 读取每张图片的bbox信息
        • 读取每张图像的segmentation信息
        • 读取人体关键点信息
    • 4.验证目标检测任务mAP


1. MS COCO数据集简介

  • 官网地址
    https://cocodataset.org/

  • 简介
    MS COCO是一个非常大型且常用的数据集,其中包括了目标检测,分割,图像描述等。其主要特性如下:

    • Object segmentation: 目标级分割
    • Recognition in context: 图像情景识别
    • Superpixel stuff segmentation: 超像素分割
    • 330K images (>200K labeled): 超过33万张图像,标注过的图像超过20万张
    • 1.5 million object instances: 150万个对象实例
    • 80 object categories: 80个目标类别
    • 91 stuff categories: 91个材料类别
    • 5 captions per image: 每张图像有5段情景描述
    • 250,000 people with keypoints: 对25万个人进行了关键点标注
      COCO_IMG
  • 注意事项

    • 这里需要注意的一个点是“什么是stuff类别”,在官方的介绍论文中是这么定义的:
      where “stuff” categories include materials and objects with no clear boundaries (sky, street, grass)
      简单的理解就是stuff中包含没有明确边界的材料和对象
    • object的80类与stuff中的91类的区别在哪?在官方的介绍论文中有如下说明:
      Note that we have limited the 2014 release to a subset of 80 categories. We did not collect segmentations for the following 11 categories: hat, shoe, eyeglasses (too many instances), mirror, window, door, street sign (ambiguous and difficult to label), plate, desk (due to confusion with bowl and dining table, respectively) and blender, hair brush (too few instances).
      简单的理解就是object80类是stuff91类的子集。对于我们自己使用,如果仅仅是做目标检测,基本只用object80类即可。
  • 简单与PASCAL VOC数据集对比
    下图是官方介绍论文中统计的对比图,通过对比很明显,不仅类别更多,每个类别标注的目标也更多。
    coco_pascalvoc

如果想进一步了解该数据集,可以去阅读下官方的介绍论文:
Microsoft COCO: Common Objects in Context https://arxiv.org/pdf/1405.0312.pdf

coco


2. MS COCO数据集下载

这里以下载coco2017数据集为例,主要下载三个文件:

  • 2017 Train images [118K/18GB]:训练过程中使用到的所有图像文件
  • 2017 Val images [5K/1GB]:验证过程中使用到的所有图像文件
  • 2017 Train/Val annotations [241MB]:对应训练集和验证集的标注json文件

下载后都解压到coco2017目录下,可以得到如下目录结构:

├── coco2017: 数据集根目录├── train2017: 所有训练图像文件夹(118287张)├── val2017: 所有验证图像文件夹(5000张)└── annotations: 对应标注文件夹├── instances_train2017.json: 对应目标检测、分割任务的训练集标注文件├── instances_val2017.json: 对应目标检测、分割任务的验证集标注文件├── captions_train2017.json: 对应图像描述的训练集标注文件├── captions_val2017.json: 对应图像描述的验证集标注文件├── person_keypoints_train2017.json: 对应人体关键点检测的训练集标注文件└── person_keypoints_val2017.json: 对应人体关键点检测的验证集标注文件夹

3. MS COCO标注文件格式

官网有给出一个关于标注文件的格式说明,可以通过以下链接查看:
https://cocodataset.org/#format-data

3.1 使用Python的json库查看

对着官方给的说明,我们可以自己用Python的json库自己读取看下,下面以读取instances_val2017.json为例:

import jsonjson_path = "/data/coco2017/annotations/instances_val2017.json"
json_labels = json.load(open(json_path, "r"))
print(json_labels["info"])

单步调试可以看到读入进来后是个字典的形式,包括了infolicensesimagesannotations以及categories信息:

coco_label

其中:

  • images是一个列表(元素个数对应图像的张数),列表中每个元素都是一个dict,对应一张图片的相关信息。包括对应图像名称图像宽度高度等信息。
    images_info

  • annotations是一个列表(元素个数对应数据集中所有标注的目标个数,注意不是图像的张数),列表中每个元素都是一个dict对应一个目标的标注信息。包括目标的分割信息polygons多边形)、目标边界框信息[x,y,width,height](左上角x,y坐标,以及宽高)目标面积对应图像id以及类别id等。iscrowd参数只有0或1两种情况,一般0代表单个对象,1代表对象集合。
    annotations_info

  • categories是一个列表(元素个数对应检测目标的类别数)列表中每个元素都是一个dict对应一个类别的目标信息。包括类别id类别名称所属超类

categories_info

3.2 使用官方cocoAPI查看

官方有给出一个读取MS COCO数据集信息的API(当然,该API还有其他重要功能),下面是对应github的连接,里面有关于该API的使用demo:
https://github.com/cocodataset/cocoapi

  • Linux系统安装pycocotools:
pip install pycocotools  
  • Windows系统安装pycocotools:
pip install pycocotools-windows

读取每张图片的bbox信息

下面是使用pycocotools读取图像以及对应bbox信息的简单示例:

import os
from pycocotools.coco import COCO
from PIL import Image, ImageDraw
import matplotlib.pyplot as pltjson_path = "/data/coco2017/annotations/instances_val2017.json"
img_path = "/data/coco2017/val2017"# load coco data
coco = COCO(annotation_file=json_path)# 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()])# 遍历前三张图像
for img_id in ids[:3]:# 获取对应图像id的所有annotations idx信息ann_ids = coco.getAnnIds(imgIds=img_id)# 根据annotations idx信息获取所有标注信息targets = coco.loadAnns(ann_ids)# get image file namepath = coco.loadImgs(img_id)[0]['file_name']# read imageimg = Image.open(os.path.join(img_path, path)).convert('RGB')draw = ImageDraw.Draw(img)# draw box to imagefor 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 imageplt.imshow(img)plt.show()

通过pycocotools读取的图像以及对应的targets信息,配合matplotlib库绘制标注图像如下:
read coco data


读取每张图像的segmentation信息

下面是使用pycocotools读取图像segmentation信息的简单示例:


import os
import randomimport numpy as np
from pycocotools.coco import COCO
from pycocotools import mask as coco_mask
from PIL import Image, ImageDraw
import matplotlib.pyplot as pltrandom.seed(0)json_path = "/data/coco2017/annotations/instances_val2017.json"
img_path = "/data/coco2017/val2017"# random pallette
pallette = [0, 0, 0] + [random.randint(0, 255) for _ in range(255*3)]# load coco data
coco = COCO(annotation_file=json_path)# 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()])# 遍历前三张图像
for img_id in ids[:3]:# 获取对应图像id的所有annotations idx信息ann_ids = coco.getAnnIds(imgIds=img_id)# 根据annotations idx信息获取所有标注信息targets = coco.loadAnns(ann_ids)# get image file namepath = coco.loadImgs(img_id)[0]['file_name']# read imageimg = Image.open(os.path.join(img_path, path)).convert('RGB')img_w, img_h = img.sizemasks = []cats = []for target in targets:cats.append(target["category_id"])  # get object class idpolygons = target["segmentation"]   # get object polygonsrles = coco_mask.frPyObjects(polygons, img_h, img_w)mask = coco_mask.decode(rles)if len(mask.shape) < 3:mask = mask[..., None]mask = mask.any(axis=2)masks.append(mask)cats = np.array(cats, dtype=np.int32)if masks:masks = np.stack(masks, axis=0)else:masks = np.zeros((0, height, width), dtype=np.uint8)# merge all instance masks into a single segmentation map# with its corresponding categoriestarget = (masks * cats[:, None, None]).max(axis=0)# discard overlapping instancestarget[masks.sum(0) > 1] = 255target = Image.fromarray(target.astype(np.uint8))target.putpalette(pallette)plt.imshow(target)plt.show()

通过pycocotools读取的图像segmentation信息,配合matplotlib库绘制标注图像如下:

在这里插入图片描述


读取人体关键点信息

在MS COCO任务中,对每个人体都标注了17的关键点,这17个关键点的部位分别如下:

["nose","left_eye","right_eye","left_ear","right_ear","left_shoulder","right_shoulder","left_elbow","right_elbow","left_wrist","right_wrist","left_hip","right_hip","left_knee","right_knee","left_ankle","right_ankle"]

在COCO给出的标注文件中,针对每个人体的标注格式如下所示。其中每3个值为一个关键点的相关信息,因为有17个关键点所以总共有51个数值。按照3个一组进行划分,前2个值代表关键点的x,y坐标,第3个值代表该关键点的可见度,它只会取 { 0 , 1 , 2 } \{0, 1, 2\} {0,1,2}三个值。0表示该点一般是在图像外无法标注,1表示虽然该点不可见但大概能猜测出位置(比如人侧着站时虽然有一只耳朵被挡住了,但大概也能猜出位置),2表示该点可见。如果第3个值为0,那么对应的x,y也都等于0:

[427, 170, 1, 429, 169, 2, 0, 0, 0, 434, 168, 2, 0, 0, 0, 441, 177, 2, 446, 177, 2, 437, 200, 2, 430, 206, 2, 430, 220, 2, 420, 215, 2, 445, 226, 2, 452, 223, 2, 447, 260, 2, 454, 257, 2, 455, 290, 2, 459, 286, 2]

下面是使用pycocotools读取图像keypoints信息的简单示例:

import numpy as np
from pycocotools.coco import COCOjson_path = "/data/coco2017/annotations/person_keypoints_val2017.json"
coco = COCO(json_path)
img_ids = list(sorted(coco.imgs.keys()))# 遍历前5张图片中的人体关键点信息(注意,并不是每张图片里都有人体信息)
for img_id in img_ids[:5]:idx = 0img_info = coco.loadImgs(img_id)[0]ann_ids = coco.getAnnIds(imgIds=img_id)anns = coco.loadAnns(ann_ids)for ann in anns:xmin, ymin, w, h = ann['bbox']# 打印人体bbox信息print(f"[image id: {img_id}] person {idx} bbox: [{xmin:.2f}, {ymin:.2f}, {xmin + w:.2f}, {ymin + h:.2f}]")keypoints_info = np.array(ann["keypoints"]).reshape([-1, 3])visible = keypoints_info[:, 2]keypoints = keypoints_info[:, :2]# 打印关键点信息以及可见度信息print(f"[image id: {img_id}] person {idx} keypoints: {keypoints.tolist()}")print(f"[image id: {img_id}] person {idx} keypoints visible: {visible.tolist()}")idx += 1

终端输出信息如下,通过以下信息可知,验证集中前5张图片里只有一张图片包含人体关键点信息:

[image id: 139] person 0 bbox: [412.80, 157.61, 465.85, 295.62]
[image id: 139] person 0 keypoints: [[427, 170], [429, 169], [0, 0], [434, 168], [0, 0], [441, 177], [446, 177], [437, 200], [430, 206], [430, 220], [420, 215], [445, 226], [452, 223], [447, 260], [454, 257], [455, 290], [459, 286]]
[image id: 139] person 0 keypoints visible: [1, 2, 0, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
[image id: 139] person 1 bbox: [384.43, 172.21, 399.55, 207.95]
[image id: 139] person 1 keypoints: [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
[image id: 139] person 1 keypoints visible: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

4.验证目标检测任务mAP

首先要弄清楚cocoapi指定的数据格式(训练网络预测的结果),在官网的Evaluate下拉框中选择Results Format,可以看到每种任务的指定数据格式要求。
coco results format这里主要讲讲针对目标检测的格式。根据官方文档给的预测结果格式可以看到,我们需要以列表的形式保存结果,列表中的每个元素对应一个检测目标(每个元素都是字典类型),每个目标记录了四个信息:

  • image_id记录该目标所属图像的id(int类型)
  • category_id记录预测该目标的类别索引,注意这里索引是对应stuff中91个类别的索引信息(int类型)
  • bbox记录预测该目标的边界框信息,注意对应目标的[xmin, ymin, width, height] (list[float]类型)
  • score记录预测该目标的概率(float类型)

下图是训练Faster R-CNN后在coco2017验证集上预测的结果:

ob format
接着将预测结果保存成json文件,后面需要使用到:

import jsonresults = []  # 所有预测的结果都保存在该list中
# write predict results into json file
json_str = json.dumps(results, indent=4)
with open('predict_results.json', 'w') as json_file:json_file.write(json_str)

数据准备:

  • COCO2017验证集json文件instances_val2017.json
    链接: https://pan.baidu.com/s/1ArWe8Igt_q0iJG6FCcH8mg 密码: sa0j
  • 自己训练的Faster R-CNN(VGG16)在验证集上预测的结果predict_results.json(刚刚上面生成的)
    链接: https://pan.baidu.com/s/1h5RksfkPFTvH82N2qN95TA 密码: 8alm

示例代码:

from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval# accumulate predictions from all images
# 载入coco2017验证集标注文件
coco_true = COCO(annotation_file="/data/coco2017/annotations/instances_val2017.json")
# 载入网络在coco2017验证集上预测的结果
coco_pre = coco_true.loadRes('predict_results.json')coco_evaluator = COCOeval(cocoGt=coco_true, cocoDt=coco_pre, iouType="bbox")
coco_evaluator.evaluate()
coco_evaluator.accumulate()
coco_evaluator.summarize()

输出结果:

loading annotations into memory...
Done (t=0.43s)
creating index...
index created!
Loading and preparing results...
DONE (t=0.65s)
creating index...
index created!
Running per image evaluation...
Evaluate annotation type *bbox*
DONE (t=21.15s).
Accumulating evaluation results...
DONE (t=2.88s).Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.233Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.415Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.233Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.104Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.262Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.323Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.216Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.319Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.327Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.145Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.361Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.463

这篇关于MS COCO数据集介绍以及pycocotools简单使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/285008

相关文章

SpringBoot中使用Flux实现流式返回的方法小结

《SpringBoot中使用Flux实现流式返回的方法小结》文章介绍流式返回(StreamingResponse)在SpringBoot中通过Flux实现,优势包括提升用户体验、降低内存消耗、支持长连... 目录背景流式返回的核心概念与优势1. 提升用户体验2. 降低内存消耗3. 支持长连接与实时通信在Sp

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安