cocoデータセットjsonファイルをxmlファイルに変換

20460 ワード

#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("")
    xml_content.append("	VOC2007")
    xml_content.append("	" + file_name + "")
    xml_content.append("	")
    xml_content.append("		" + str(width) + "")
    xml_content.append("		" + str(height) + "")
    xml_content.append("	")
    xml_content.append("	0")
    #   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("	")
        xml_content.append("		" + cate_name + "")
        xml_content.append("		Unspecified")
        xml_content.append("		0")
        xml_content.append("		0")
        xml_content.append("		")
        xml_content.append("			" + str(int(bbox[0])) + "")
        xml_content.append("			" + str(int(bbox[1])) + "")
        xml_content.append("			" + str(int(bbox[0] + bbox[2])) + "")
        xml_content.append("			" + str(int(bbox[1] + bbox[3])) + "")
        xml_content.append("		")
        xml_content.append("	")
    xml_content.append("")

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

本文は主に博文を参考にします:夢飛天