coco数据集 json文件转化为xml文件

#translate coco_json to xml
#使用时仅需修改21、22、24行路径文件
import os
import time
import json
import pandas as pd
from tqdm import tqdm
from pycocotools.coco import COCO

def trans_id(category_id):
    names = []
    namesid = []
    for i in range(0, len(cats)):
        names.append(cats[i]['name'])
        namesid.append(cats[i]['id'])
        #print('id:{1}\t {0}'.format(names[i], namesid[i]))
    index = namesid.index(category_id)
    return index


root = '/home/***/datasets/COCO/coco2017/'  # 你下载的 COCO 数据集所在目录
dataType = 'train2017'
anno  = '{}/annotations/instances_{}.json'.format(root, dataType)
xml_dir = '{}/xml/{}_xml'.format(root, dataType)

coco = COCO(anno)  # 读文件
cats = coco.loadCats(coco.getCatIds())  # 这里loadCats就是coco提供的接口,获取类别



# Create anno dir
dttm = time.strftime("%Y%m%d%H%M%S", time.localtime())
if os.path.exists(xml_dir):
    os.rename(xml_dir, xml_dir + dttm)
os.mkdir(xml_dir)


with open(anno, 'r') as load_f:
    f = json.load(load_f)

imgs = f['images']

df_cate = pd.DataFrame(f['categories'])
df_cate_sort = df_cate.sort_values(["id"], ascending=True)
categories = list(df_cate_sort['name'])
print('categories = ',categories)
df_anno = pd.DataFrame(f['annotations'])



for i in tqdm(range(len(imgs))):
    xml_content = []
    file_name = imgs[i]['file_name']
    height = imgs[i]['height']
    img_id = imgs[i]['id']
    width = imgs[i]['width']

    xml_content.append("<annotation>")
    xml_content.append("	<folder>VOC2007</folder>")
    xml_content.append("	<filename>" + file_name + "</filename>")
    xml_content.append("	<size>")
    xml_content.append("		<width>" + str(width) + "</width>")
    xml_content.append("		<height>" + str(height) + "</height>")
    xml_content.append("	</size>")
    xml_content.append("	<segmented>0</segmented>")
    # 通过img_id找到annotations
    annos = df_anno[df_anno["image_id"].isin([img_id])]

    for index, row in annos.iterrows():
        bbox = row["bbox"]
        category_id = row["category_id"]
        cate_name = categories[trans_id(category_id)]
      
        # add new object
        xml_content.append("	<object>")
        xml_content.append("		<name>" + cate_name + "</name>")
        xml_content.append("		<pose>Unspecified</pose>")
        xml_content.append("		<truncated>0</truncated>")
        xml_content.append("		<difficult>0</difficult>")
        xml_content.append("		<bndbox>")
        xml_content.append("			<xmin>" + str(int(bbox[0])) + "</xmin>")
        xml_content.append("			<ymin>" + str(int(bbox[1])) + "</ymin>")
        xml_content.append("			<xmax>" + str(int(bbox[0] + bbox[2])) + "</xmax>")
        xml_content.append("			<ymax>" + str(int(bbox[1] + bbox[3])) + "</ymax>")
        xml_content.append("		</bndbox>")
        xml_content.append("	</object>")
    xml_content.append("</annotation>")

    x = xml_content
    xml_content = [x[i] for i in range(0, len(x)) if x[i] != "\n"]
    ### list存入文件
    xml_path = os.path.join(xml_dir, file_name.replace('.jpg', '.xml'))
    with open(xml_path, 'w+', encoding="utf8") as f:
        f.write('\n'.join(xml_content))
    xml_content[:] = []

本文主要参考博文:梦飞天

COCO数据集是一个广泛使用的大型数据集,它包含了丰富的图像识别、分割和标注信息。COCO数据集中的标注信息可以用于实例分割任务,实例分割是要求对图像中的每个目标实例进行准确分割的任务。COCO数据集中通常使用JSON格式来保存标注信息。 将COCO数据集JSON标注转化为实例分割数据集,通常需要遵循以下步骤: 1. 读取JSON文件:首先需要读取COCO数据集JSON文件,这些文件包含了有关图像和标注的各种信息,例如图像的尺寸、标注的类别、轮廓信息等。 2. 解析标注信息:JSON文件中的`annotations`字段包含了每个实例的标注信息,其中`segmentation`字段描述了目标实例的轮廓。对于实例分割,`segmentation`字段通常包含一个或多个轮廓的多边形坐标列表。这些坐标是相对于原图的像素坐标。 3. 换坐标:根据标注中的坐标信息,需要将这些坐标换为与目标图像尺寸匹配的遮罩(mask)。遮罩是一个二维数组,其中每个像素点对应图像中的一个像素,标注的实例对应的像素位置会被标记为1(或其他指定的正整数),背景像素则为0。 4. 保存遮罩:将得到的遮罩保存为适当的格式,比如PNG图像,其中遮罩的每个像素对应一个像素值,用于表示不同实例。 5. 创建数据集结构:最后,将图像文件与对应的遮罩文件关联起来,创建实例分割数据集。通常包括图像文件夹、遮罩文件夹、图像名称列表等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值