COCO数据集格式(详解)及COCO标注可视化。json转COCO等代码

2023-11-19

coco数据集JSON文件格式分为一下几个字段。

{
    "info": info, # dict
     "licenses": [license], # list ,内部是dict
     "images": [image], # list ,内部是dict
     "annotations": [annotation], # list ,内部是dict
     "categories": # list ,内部是dict
 }

注意 :对于深度学习训练,实际有用的字段,只有以下三个字段。

"images": [image], # list ,内部是dict
     "annotations": [annotation], # list ,内部是dict
     "categories": # list ,内部是dict

info字段内的内容

"info":{#数据信息描述
        "description":"COCO 2017 Dataset",# 数据描述
        "url":"http://*****.org",#下载地址
        "version":"1.0",#版本
        "year":"2017",#年份
        "contributor":"COCO Consortium",#提供者
        "data_created":"2017/09/01",#创建日期}

这个字段可以忽略,可以为空。

licenses字段

"licenses":[
            {
             'url': 'http://creativecommons.org/licenses/by-nc-sa/2.0/',
             'id': 1,
             'name': 'Attribution-NonCommercial-ShareAlike License'
            }
            ....
            ....
            ]

这个字段可以忽略,可以为空。

images

"images": [
            {
             "license":4 #可以忽略
            "file_name":000.jpg #可以忽略
            "coco_url":"http://****" #可以忽略
             "id": 1, 
             "file_name": "000.tif", 
             "width": 48.0, 
             "height": 112.0
             "date_captured":"2022-02-02 17:02:02" #可以忽略
             "flickl_url":"http://****" #可以忽略
            }
            ...
            ...
            ]

annotations

这个字段里面都是有用信息

categories

这个里面也是有用的信息

 将一个大的json文件生成只有一张图片的json:

from __future__ import print_function
from pycocotools.coco import COCO
import os, sys, zipfile
import urllib.request
import shutil
import numpy as np
import skimage.io as io
import matplotlib.pyplot as plt
import pylab
import json
json_file='/media/fire/d/share_data/datasets/coco/annotations/person_keypoints_val2017.json' #
# Object Instance 类型的标注
# person_keypoints_val2017.json  
# Object Keypoint 类型的标注格式
# captions_val2017.json  
# Image Caption的标注格式
data=json.load(open(json_file,'r'))
data_2={}
data_2['info']=data['info']
data_2['licenses']=data['licenses']
data_2['images']=[data['images'][0]] # 只提取第一张图片
data_2['categories']=data['categories']
annotation=[] # 通过imgID 找到其所有对象
imgID=data_2['images'][0]['id']
for ann in data['annotations']:
    if ann['image_id']==imgID:
        annotation.append(ann)
data_2['annotations']=annotation # 保存到新的JSON文件,便于查看数据特点
json.dump(data_2,open('/media/fire/d/share_data/datasets/coco/annotations/test_person_keypoints_val2017.json','w'),indent=4) # indent=4 更加美观显示

二、COCO数据集可视化

from __future__ import print_function
from pycocotools.coco import COCO
import os, sys, zipfile
import urllib.request
import shutil
import numpy as np
import skimage.io as io
import matplotlib.pyplot as plt
import pylab
pylab.rcParams['figure.figsize'] = (8.0, 10.0)
annFile='/media/fire/d/share_data/datasets/coco/annotations/person_keypoints_val2017.json'
coco=COCO(annFile) # display COCO categories and supercategories
cats = coco.loadCats(coco.getCatIds())
nms=[cat['name'] for cat in cats]
print('COCO categories: \n{}\n'.format(' '.join(nms)))
nms = set([cat['supercategory'] for cat in cats])
print('COCO supercategories: \n{}'.format(' '.join(nms)))
# imgIds = coco.getImgIds(imgIds = [324158])
imgIds = coco.getImgIds()
img = coco.loadImgs(imgIds[0])[0]
dataDir = '/media/fire/d/share_data/datasets/coco'
dataType = 'val2017'
I = io.imread('%s/%s/%s'%(dataDir,dataType,img['file_name']))
#plt.axis('off')
plt.imshow(I)
plt.show()

显示图片

 加载肢体关键点:

catIds=[]
for ann in coco.dataset['annotations']:
    if ann['image_id']==imgIds[0]:
        catIds.append(ann['category_id'])
plt.imshow(I);
plt.axis('off')
annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None)
anns = coco.loadAnns(annIds)
print(anns)
coco.showAnns(anns)
plt.imshow(I); plt.axis('off'); plt.show()

加载instances mask:

coco = COCO("/media/fire/d/share_data/datasets/coco/annotations/instances_val2017.json")

img_ids = coco.getImgIds()
print(len(img_ids))
cat_ids = []
for ann in coco.dataset["annotations"]:
    if ann["image_id"] == img_ids[0]:
        cat_ids.append(ann["category_id"])
ann_ids = coco.getAnnIds(imgIds=img_ids[0], catIds = cat_ids)
ann_ids2 = coco.getAnnIds(imgIds=img_ids[0], catIds = cat_ids)
plt.imshow(I)
print(ann_ids)
print(ann_ids2)
anns = coco.loadAnns(ann_ids)
coco.showAnns(anns)
plt.imshow(I)
plt.show()

图像效果

三、不同标注数据转换到COCO格式

下面为labelme json格式转到COCO格式。

def image(self,data,num):
    image={}
    img = utils.img_b64_to_array(data['imageData']) # 解析原图片数据
    # img=io.imread(data['imagePath'])
    # 通过图片路径打开图片 # img = cv2.imread(data['imagePath'], 0)
    height, width = img.shape[:2]
    img = None
    image['height']=height
    image['width'] = width
    image['id']=num+1
    image['file_name'] = data['imagePath'].split('/')[-1]
    self.height=height
    self.width=width
    return image
def categorie(self,label):
    categorie={}
    categorie['supercategory'] = label[0]
    categorie['id']=len(self.label)+1 # 0 默认为背景
    categorie['name'] = label[1]
    return categorie

def annotation(self,points,label,num):
    annotation={}
    annotation['segmentation']=[list(np.asarray(points).flatten())]
    annotation['iscrowd'] = 0
    annotation['image_id'] = num+1
    # annotation['bbox'] = str(self.getbbox(points))
    # 使用list保存json文件时报错(不知道为什么)
    # list(map(int,a[1:-1].split(','))) a=annotation['bbox'] 使用该方式转成list
    annotation['bbox'] = list(map(float,self.getbbox(points)))
    annotation['category_id'] = self.getcatid(label)
    annotation['id'] = self.annID
    return annotation

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

COCO数据集格式(详解)及COCO标注可视化。json转COCO等代码 的相关文章

  • (discord.py) 尝试更改成员角色时,“用户”对象没有属性“角色”

    因此 我正在尝试编写一个机器人 让某人在命令中指定的主持人指定的一段时间内暂停角色 我知道该变量称为 小时 即使它目前以秒为单位 我稍后会解决这个问题 基本上 它是由主持人在消息 暂停 personmention numberofhours
  • Python BigQuery 存储。并行读取多个流

    我有以下玩具代码 import pandas as pd from google cloud import bigquery storage v1beta1 import os import google auth os environ G
  • Django REST序列化器:创建对象而不保存

    我已经开始使用 Django REST 框架 我想做的是使用一些 JSON 发布请求 从中创建一个 Django 模型对象 然后使用该对象而不保存它 我的 Django 模型称为 SearchRequest 我所拥有的是 api view
  • 如何在python中读取多个文件中的文本

    我的文件夹中有许多文本文件 大约有 3000 个文件 每个文件中第 193 行是唯一包含重要信息的行 我如何使用 python 将所有这些文件读入 1 个文本文件 os 模块中有一个名为 list dir 的函数 该函数返回给定目录中所有文
  • Python、Tkinter、更改标签颜色

    有没有一种简单的方法来更改按钮中文本的颜色 I use button text input text here 更改按下后按钮文本的内容 是否存在类似的颜色变化 button color red Use the foreground设置按钮
  • Flask 和 uWSGI - 无法加载应用程序 0 (mountpoint='')(找不到可调用或导入错误)

    当我尝试使用 uWSGI 启动 Flask 时 出现以下错误 我是这样开始的 gt cd gt root localhost uwsgi socket 127 0 0 1 6000 file path to folder run py ca
  • 更改自动插入 tkinter 小部件的文本颜色

    我有一个文本框小部件 其中插入了三条消息 一条是开始消息 一条是结束消息 一条是在 单位 被摧毁时发出警报的消息 我希望开始和结束消息是黑色的 但被毁坏的消息 参见我在代码中评论的位置 插入小部件时颜色为红色 我不太确定如何去做这件事 我看
  • pandas 替换多个值

    以下是示例数据框 gt gt gt df pd DataFrame a 1 1 1 2 2 b 11 22 33 44 55 gt gt gt df a b 0 1 11 1 1 22 2 1 33 3 2 44 4 3 55 现在我想根据
  • 打破嵌套循环[重复]

    这个问题在这里已经有答案了 有没有比抛出异常更简单的方法来打破嵌套循环 在Perl https en wikipedia org wiki Perl 您可以为每个循环指定标签 并且至少继续一个外循环 for x in range 10 fo
  • __del__ 真的是析构函数吗?

    我主要用 C 做事情 其中 析构函数方法实际上是为了销毁所获取的资源 最近我开始使用python 这真的很有趣而且很棒 我开始了解到它有像java一样的GC 因此 没有过分强调对象所有权 构造和销毁 据我所知 init 方法对我来说在 py
  • 安装后 Anaconda 提示损坏

    我刚刚安装张量流GPU创建单独的后环境按照以下指示here https github com antoniosehk keras tensorflow windows installation 但是 安装后当我关闭提示窗口并打开新航站楼弹出
  • NameError:名称“urllib”未定义”

    CODE import networkx as net from urllib request import urlopen def read lj friends g name fetch the friend list from Liv
  • 在pyyaml中表示具有相同基类的不同类的实例

    我有一些单元测试集 希望将每个测试运行的结果存储为 YAML 文件以供进一步分析 YAML 格式的转储数据在几个方面满足我的需求 但测试属于不同的套装 结果有不同的父类 这是我所拥有的示例 gt gt gt rz shorthand for
  • Python:字符串不会转换为浮点数[重复]

    这个问题在这里已经有答案了 我几个小时前写了这个程序 while True print What would you like me to double line raw input gt if line done break else f
  • Numpy 优化

    我有一个根据条件分配值的函数 我的数据集大小通常在 30 50k 范围内 我不确定这是否是使用 numpy 的正确方法 但是当数字超过 5k 时 它会变得非常慢 有没有更好的方法让它更快 import numpy as np N 5000
  • VSCode:调试配置中的 Python 路径无效

    对 Python 和 VSCode 以及 stackoverflow 非常陌生 直到最近 我已经使用了大约 3 个月 一切都很好 当尝试在调试器中运行任何基本的 Python 程序时 弹出窗口The Python path in your
  • glpk.LPX 向后兼容性?

    较新版本的glpk没有LPXapi 旧包需要它 我如何使用旧包 例如COBRA http opencobra sourceforge net openCOBRA Welcome html 与较新版本的glpk 注意COBRA适用于 MATL
  • 您可以在 Python 类型注释中指定方差吗?

    你能发现下面代码中的错误吗 米皮不能 from typing import Dict Any def add items d Dict str Any gt None d foo 5 d Dict str str add items d f
  • Spark.read 在 Databricks 中给出 KrbException

    我正在尝试从 databricks 笔记本连接到 SQL 数据库 以下是我的代码 jdbcDF spark read format com microsoft sqlserver jdbc spark option url jdbc sql
  • Python - 字典和列表相交

    给定以下数据结构 找出这两种数据结构共有的交集键的最有效方法是什么 dict1 2A 3A 4B list1 2A 4B Expected output 2A 4B 如果这也能产生更快的输出 我可以将列表 不是 dict1 组织到任何其他数

随机推荐