栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

将COCO数据集json格式文件转为VOC数据集xml格式

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将COCO数据集json格式文件转为VOC数据集xml格式

由于之前使用Mask R-CNN数据集是coco格式的,现在用YOLO需要voc格式的数据集,重新制作样本太麻烦,所以直接用python代码转换。

1.首先要把一个整的json文件分为单个的,因为coco数据集是把全部标签整合到一个文件的

我的数据集较小,所以是一次一次提取的,如果数据集较大的话可以自己改成循环。

from __future__ import print_function
import json
json_file='F:/研究生/研一/计算机视觉/mask-rcnn/test/annotations/instances_val.json' #
# Object Instance 类型的标注
# person_keypoints_val2017.json
# Object Keypoint 类型的标注格式
# captions_val2017.json
# Image Caption的标注格式
data=json.load(open(json_file,'r'))
data_2={}
# da ta_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('F:/研究生/研一/计算机视觉/mask-rcnn/test/annotations/1.json','w'),indent=4) # indent=4 更加美观显示
2.然后是json到xml的格式转换

运行下面代码前,需要先创建好几个文件夹:
创建dataset文件夹,在dataset文件下再创建一个images文件夹和一个labels文件夹,其中images里存放jpg格式的图片(注意是jpg!),labels里存放拆分好的json格式的标签。
在dataset同级目录下创建用于格式转换的py文件。
运行完代码后,会自动生成VOC2007的文件夹,里面有划分好的训练集,验证集和测试集,生成好的voc数据集就可以直接拿到YOLO网络里训练啦。
(注:下面代码需要根据自己的json标签稍微修改一些参数)

import os
import numpy as np
import codecs
import json
from glob import glob
import cv2
import shutil
from sklearn.model_selection import train_test_split

# 1.存放的json标签路径
labelme_path = "labelmedataset/labels/"

# 原始labelme标注数据路径
saved_path = "VOC2007/"
# 保存路径
isUseTest = True  # 是否创建test集

# 2.创建要求文件夹
if not os.path.exists(saved_path + "Annotations"):
    os.makedirs(saved_path + "Annotations")
if not os.path.exists(saved_path + "JPEGImages/"):
    os.makedirs(saved_path + "JPEGImages/")
if not os.path.exists(saved_path + "ImageSets/Main/"):
    os.makedirs(saved_path + "ImageSets/Main/")

# 3.获取待处理文件
files = glob(labelme_path + "*.json")
files = [i.replace("\", "/").split("/")[-1].split(".json")[0] for i in files]
print(files)

# 4.读取标注信息并写入 xml
for json_file_ in files:
    json_filename = labelme_path + json_file_ + ".json"
    json_file = json.load(open(json_filename, "r", encoding="utf-8"))
    height, width, channels = cv2.imread('labelmedataset/images/' + json_file_ + ".jpg").shape
    with codecs.open(saved_path + "Annotations/" + json_file_ + ".xml", "w", "utf-8") as xml:

        xml.write('n')
        xml.write('t' + 'CELL_data' + 'n')
        xml.write('t' + json_file_ + ".jpg" + 'n')
        xml.write('tn')
        xml.write('ttCELL Datan')
        xml.write('ttCELLn')
        xml.write('ttbloodcelln')
        xml.write('ttNULLn')
        xml.write('tn')
        xml.write('tn')
        xml.write('ttNULLn')
        xml.write('ttCELLn')
        xml.write('tn')
        xml.write('tn')
        xml.write('tt' + str(width) + 'n')
        xml.write('tt' + str(height) + 'n')
        xml.write('tt' + str(channels) + 'n')
        xml.write('tn')
        xml.write('tt0n')# 是否用于分割(在图像物体识别中01无所谓)
        cName = json_file["categories"]
        Name = cName[0]["name"]
        print(Name)
        for multi in json_file["annotations"]:
            points = np.array(multi["bbox"])
            labelName = Name
            xmin = points[0]
            xmax = points[0]+points[2]
            ymin = points[1]
            ymax = points[1]+points[3]
            label = Name
            if xmax <= xmin:
                pass
            elif ymax <= ymin:
                pass
            else:
                xml.write('tn')
                xml.write('tt' + labelName + 'n')# 物体类别
                xml.write('ttUnspecifiedn')# 拍摄角度
                xml.write('tt0n')# 是否被截断(0表示完整)
                xml.write('tt0n')# 目标是否难以识别(0表示容易识别)
                xml.write('ttn')
                xml.write('ttt' + str(int(xmin)) + 'n')
                xml.write('ttt' + str(int(ymin)) + 'n')
                xml.write('ttt' + str(int(xmax)) + 'n')
                xml.write('ttt' + str(int(ymax)) + 'n')
                xml.write('ttn')
                xml.write('tn')
                print(json_filename, xmin, ymin, xmax, ymax, label)
        xml.write('')

# 5.复制图片到 VOC2007/JPEGImages/下
image_files = glob("labelmedataset/images/" + "*.jpg")
print("copy image files to VOC007/JPEGImages/")
for image in image_files:
    shutil.copy(image, saved_path + "JPEGImages/")

# 6.拆分训练集、测试集、验证集
txtsavepath = saved_path + "ImageSets/Main/"
ftrainval = open(txtsavepath + '/trainval.txt', 'w')
ftest = open(txtsavepath + '/test.txt', 'w')
ftrain = open(txtsavepath + '/train.txt', 'w')
fval = open(txtsavepath + '/val.txt', 'w')
total_files = glob("./VOC2007/Annotations/*.xml")
total_files = [i.replace("\", "/").split("/")[-1].split(".xml")[0] for i in total_files]
trainval_files = []
test_files = []
if isUseTest:
    trainval_files, test_files = train_test_split(total_files, test_size=0.15, random_state=55)
else:
    trainval_files = total_files
for file in trainval_files:
    ftrainval.write(file + "n")

# split
train_files, val_files = train_test_split(trainval_files, test_size=0.15, random_state=55)

# train
for file in train_files:
    ftrain.write(file + "n")

# val
for file in val_files:
    print(file)
    fval.write(file + "n")
for file in test_files:
    print("test:"+file)
    ftest.write(file + "n")
ftrainval.close()
ftrain.close()
fval.close()
ftest.close()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/767058.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号