COCO.JSON文件解析

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

打开JSON文件查看数据特点

由于JSON文件太大,很多都是重复定义的,所以只提取一张图片,存储成新的JSON文件,便于观察。

# -*- coding:utf-8 -*-

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='./annotations/instances_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('./new_instances_val2017.json','w'),indent=4) # indent=4 更加美观显示

主要有以下几个字段:

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

info

"info": { # 数据集信息描述
        "description": "COCO 2017 Dataset", # 数据集描述
        "url": "http://cocodataset.org", # 下载地址
        "version": "1.0", # 版本
        "year": 2017, # 年份
        "contributor": "COCO Consortium", # 提供者
        "date_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": "000000397133.jpg", # 图片名
            "coco_url":  "http://images.cocodataset.org/val2017/000000397133.jpg",# 网路地址路径
            "height": 427, # 高
            "width": 640, # 宽
            "date_captured": "2013-11-14 17:02:52", # 数据获取日期
            "flickr_url": "http://farm7.staticflickr.com/6116/6255196340_da26cf2c9e_z.jpg",# flickr网路地址
            "id": 397133 # 图片的ID编号(每张图片ID是唯一的)
        },
        ……
        ……
    ],

categories

"categories": [ # 类别描述
        {
            "supercategory": "person", # 主类别
            "id": 1, # 类对应的id (0 默认为背景)
            "name": "person" # 子类别
        },
        {
            "supercategory": "vehicle", 
            "id": 2,
            "name": "bicycle"
        },
        {
            "supercategory": "vehicle",
            "id": 3,
            "name": "car"
        },
        ……
        ……
    ],

: bicycle 与car都属于vehicle,但两者又属于不同的类别。例如:羊(主类别)分为山羊、绵羊、藏羚羊(子类别)等

annotations

"annotation": [
        {
            "segmentation": [ # 对象的边界点(边界多边形)
                [
                    224.24,297.18,# 第一个点 x,y坐标
                    228.29,297.18, # 第二个点 x,y坐标
                    234.91,298.29,
                    ……
                    ……
                    225.34,297.55
                ]
            ],
            "area": 1481.3806499999994, # 区域面积
            "iscrowd": 0, # 
            "image_id": 397133, # 对应的图片ID(与images中的ID对应)
            "bbox": [217.62,240.54,38.99,57.75], # 定位边框 [x,y,w,h]
            "category_id": 44, # 类别ID(与categories中的ID对应)
            "id": 82445 # 对象ID,因为每一个图像有不止一个对象,所以要对每一个对象编号(每个对象的ID是唯一的)
        },
        ……
        ……
        ]

注意,单个的对象(iscrowd=0)可能需要多个polygon来表示,比如这个对象在图像中被挡住了。而iscrowd=1时(将标注一组对象,比如一群人)的segmentation使用的就是RLE格式。

### 获取或使用 VOC2012 数据集 JSON 文件 VOC2012 数据集本身并不提供 JSON 格式的标注文件,而是主要采用 XML 格式来存储图像的标注信息。然而,在某些情况下,为了与其他工具或框架兼容(如 COCO),可能需要将这些 XML 文件转换成 JSON 格式。 #### 转换方法 可以编写 Python 脚本来实现从 XML 到 JSON 的转换过程。下面是一个简单的例子: ```python import xml.etree.ElementTree as ET import json import os def parse_xml_to_dict(xml_file): tree = ET.parse(xml_file) root = tree.getroot() data = {} for child in root: if len(child) == 0: data[child.tag] = child.text else: sub_data = [] for item in child: temp = {item.tag: item.text} sub_data.append(temp) data[child.tag] = sub_data return data def convert_voc_to_coco(voc_dir, output_json_path): annotations = [] for filename in os.listdir(voc_dir): if not filename.endswith('.xml'): continue file_path = os.path.join(voc_dir, filename) annotation = parse_xml_to_dict(file_path) image_info = { "file_name": f"{annotation['filename']}.jpg", "height": int(annotation["size"][0]["height"]), "width": int(annotation["size"][0]["width"]) } objects = annotation.get('object', []) bboxes = [] categories = set() for obj in objects: bbox = [ float(obj['bndbox'][0]['xmin']), float(obj['bndbox'][0]['ymin']), float(obj['bndbox'][0]['xmax']) - float(obj['bndbox'][0]['xmin']), float(obj['bndbox'][0]['ymax']) - float(obj['bndbox'][0]['ymin']) ] category_id = obj['name'] categories.add(category_id) bboxes.append({ 'bbox': bbox, 'category_id': category_id }) coco_format_annotation = { "image": image_info, "annotations": bboxes, "categories": [{"id": cat} for cat in list(categories)] } annotations.append(coco_format_annotation) with open(output_json_path, 'w') as outfile: json.dump(annotations, outfile, indent=4) convert_voc_to_coco('/path/to/voc/xml/files/', '/output/path/coco_style_annotations.json') ``` 这段代码会读取指定目录下的所有 `.xml` 文件,并将其解析为字典形式;接着构建符合 COCO API 输入格式的数据结构并保存至 JSON 文件中[^1]。 需要注意的是,上述脚本仅作为基础模板展示,实际应用时还需要根据具体需求调整字段名称、处理特殊情况等逻辑细节。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值