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

2023-09-20 16:36:53

1、MS COCO数据集简介

在这里插入图片描述
在这里插入图片描述

2、MS COCO数据集目录结构

在这里插入图片描述

├── 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标注文件格式

3.1 使用Python的json库查看

在这里插入图片描述

import json

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

在这里插入图片描述
在这里插入图片描述

3.2 使用官方cocoAPI查看

安装:

# ubuntu
pip install pycocotools  
# Windows
pip install pycocotools-windows

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

import os
from pycocotools.coco import COCO
from PIL import Image, ImageDraw
import matplotlib.pyplot as plt

json_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 name
    path = coco.loadImgs(img_id)[0]['file_name']

    # read image
    img = Image.open(os.path.join(img_path, 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()

通过pycocotools读取的图像以及对应的targets信息,配合matplotlib库绘制标注图像如下:
在这里插入图片描述
读取每张图像的segmentation信息

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


import os
import random

import numpy as np
from pycocotools.coco import COCO
from pycocotools import mask as coco_mask
from PIL import Image, ImageDraw
import matplotlib.pyplot as plt

random.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 name
    path = coco.loadImgs(img_id)[0]['file_name']
    # read image
    img = Image.open(os.path.join(img_path, path)).convert('RGB')
    img_w, img_h = img.size

    masks = []
    cats = []
    for target in targets:
        cats.append(target["category_id"])  # get object class id
        polygons = target["segmentation"]   # get object polygons
        rles = 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 categories
    target = (masks * cats[:, None, None]).max(axis=0)
    # discard overlapping instances
    target[masks.sum(0) > 1] = 255
    target = Image.fromarray(target.astype(np.uint8))
	# 使用putpalette()函数,而且我们可以自定义各个类别区域的颜色。
	# putpalette给对象加上调色板,相当于上色:R,G,B
    # 三个数一组,对应于RGB通道,可以自己定义标签颜色
    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"]

在这里插入图片描述

[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 COCO

json_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 = 0
    img_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

在这里插入图片描述

4、目标检测验证任务mAP

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

import json

results = []  # 所有预测的结果都保存在该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.233
 Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.415
 Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.233
 Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.104
 Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.262
 Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.323
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.216
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.319
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.327
 Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.145
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.361
 Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.463
更多推荐

【问题记录】解决Git上传文件到GitHub时收到 “GH001: Large files detected” 错误信息!

环境Windows11家庭中文版gitversion2.41.0.windows.1GitHub问题情况在命令行中使用git上传pdf文件到GitHub服务器时,提示了如下警告信息:原因是GitHub有一个文件大小限制,通常为100MB。如果尝试上传大于此限制的文件,GitHub将拒绝接受这个文件。如果上传大于50MB

【面试经典150 | 数组】多数元素

文章目录写在前面Tag题目来源题目解读解题思路方法一:哈希表方法二:排序方法三:摩尔投票法写在最后写在前面本专栏专注于分析与讲解【面试经典150】算法,两到三天更新一篇文章,欢迎催更……专栏内容以分析题目为主,并附带一些对于本题涉及到的数据结构等内容进行回顾与总结,文章结构大致如下,部分内容会有增删:Tag:介绍本题牵

淘宝问问:电商AI,重新定义购物体验

AI大模型进展的如火如荼,怎么少得了电商平台的参与,淘宝率先打响了第一枪。每一个软件都会有自己的Copilot,淘宝的就叫“淘宝问问”。用户可以在淘宝上使用“淘宝问问”来获取商品信息、价格、评价等,当前是内测版,虽有惊喜,但终究是刚刚发布内测,能力上还有待提升。淘宝问问通过语音、文字的方式进行交互,除基于通义千问的AI

Vue3 环境变量

文章目录前言一、环境变量简介二、自定义环境变量生产环境预览三、vite配置文件读取环境变量总结前言本文主要记录在项目中如何定义环境变量,达到不同环境中有不同的效果以及在vite配置文件中读取环境变量的方法。一、环境变量简介场景:各个环境下存在某些差异,比如请求地址不同,方便测试做的一些测试功能,这些在不同环境下都是不同

微信小程序如何在切换页面后原页面状态不变

在微信小程序中,如果要实现在切换页面后原页面状态不变,可以通过以下几种方式来实现:使用全局数据:可以将需要保持状态的数据存储在小程序的全局数据中,这样无论切换到哪个页面,都可以通过全局数据来获取之前保存的状态。//在app.js中定义全局数据App({globalData:{status:'default'}})在原页

如何在浏览器中导入Excel表格插件

如何在Vue框架中集成在线表格编辑器(designer)在Vue中集成在线表格编辑器:本节内容小编将为大家介绍Vue框架中如何集成在线表格编辑器和如何实现使用编辑器实现表格数据绑定。Vue集成在线表格编辑器和SpreadJS的方法相似,首先引入需要集成到Vue中的资源,其次使用styleInfo标签和designerI

pycharm安装jupyter,用德古拉主题,但是输入行全白了,看不清,怎么办?

问题描述今天换了以下pycharm主题,但是jupyter界面输入代码行太白了,白到看不清楚这行的字,更不知道写的是什么,写到哪了,这还是挺烦人的,其他都挺正常的。问题分析目前来看有两个原因:1、pycharm还没反应过来,重启下或许就好了(但是我重启好几次都没有解决)2、editor的问题,editor可能是本身就把

数据结构与算法:排序算法(1)

目录冒泡排序思想代码实现优化鸡尾酒排序优缺点适用场景快速排序介绍流程基准元素选择元素交换1.双边循环法使用流程代码实现2.单边循环法使用流程代码实现3.非递归实现排序在生活中无处不在,看似简单,背后却隐藏着多种多样的算法和思想;根据时间复杂度的不同,主流的排序算法可以分为三大类:1.时间复杂度为O(n^2)的排序算法冒

Prometheus+Consul 自助服务发现

Prometheus官网https://prometheus.io/download/Consul介绍Consul是基于GO语言开发的开源工具,主要面向分布式,服务化的系统提供服务注册、服务发现和配置管理的功能。Consul提供服务注册/发现、健康检查、Key/Value存储、多数据中心和分布式一致性保证等功能。通过P

Qt/C++音视频开发55-加密保存到文件并解密播放

一、前言为了保证视频文件的安全性,有时候需要对保存的视频文件加密,然后播放的时候解密出来再播放,只有加密解密的秘钥一致时才能正常播放,用ffmpeg做视频文件的加密保存和解密播放比较简单,基于ffmpeg强大的字典参数设计,在avformat_write_header写入头部数据的时候,可以通过万能的av_dict_s

Redis的String常用命令

Redis基础知识不想key被更改,再key的后面加上nx.eg:127.0.0.1:6379>sets11OK127.0.0.1:6379>setss111OK127.0.0.1:6379>renamenxsss(integer)0--显示的结果为0,表示这个键在的时候,不可修改127.0.0.1:6379>判断命令

热文推荐