由于之前使用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'
data=json.load(open(json_file,'r'))
data_2={}
data_2['images']=[data['images'][0]]
data_2['categories']=data['categories']
annotation=[]
imgID=data_2['images'][0]['id']
for ann in data['annotations']:
if ann['image_id']==imgID:
annotation.append(ann)
data_2['annotations']=annotation
json.dump(data_2,open('F:/研究生/研一/计算机视觉/mask-rcnn/test/annotations/1.json','w'),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
labelme_path = "labelmedataset/labels/"
saved_path = "VOC2007/"
isUseTest = True
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/")
files = glob(labelme_path + "*.json")
files = [i.replace("\\", "/").split("/")[-1].split(".json")[0] for i in files]
print(files)
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('<annotation>\n')
xml.write('\t<folder>' + 'CELL_data' + '</folder>\n')
xml.write('\t<filename>' + json_file_ + ".jpg" + '</filename>\n')
xml.write('\t<source>\n')
xml.write('\t\t<database>CELL Data</database>\n')
xml.write('\t\t<annotation>CELL</annotation>\n')
xml.write('\t\t<image>bloodcell</image>\n')
xml.write('\t\t<flickrid>NULL</flickrid>\n')
xml.write('\t</source>\n')
xml.write('\t<owner>\n')
xml.write('\t\t<flickrid>NULL</flickrid>\n')
xml.write('\t\t<name>CELL</name>\n')
xml.write('\t</owner>\n')
xml.write('\t<size>\n')
xml.write('\t\t<width>' + str(width) + '</width>\n')
xml.write('\t\t<height>' + str(height) + '</height>\n')
xml.write('\t\t<depth>' + str(channels) + '</depth>\n')
xml.write('\t</size>\n')
xml.write('\t\t<segmented>0</segmented>\n')
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('\t<object>\n')
xml.write('\t\t<name>' + labelName + '</name>\n')
xml.write('\t\t<pose>Unspecified</pose>\n')
xml.write('\t\t<truncated>0</truncated>\n')
xml.write('\t\t<difficult>0</difficult>\n')
xml.write('\t\t<bndbox>\n')
xml.write('\t\t\t<xmin>' + str(int(xmin)) + '</xmin>\n')
xml.write('\t\t\t<ymin>' + str(int(ymin)) + '</ymin>\n')
xml.write('\t\t\t<xmax>' + str(int(xmax)) + '</xmax>\n')
xml.write('\t\t\t<ymax>' + str(int(ymax)) + '</ymax>\n')
xml.write('\t\t</bndbox>\n')
xml.write('\t</object>\n')
print(json_filename, xmin, ymin, xmax, ymax, label)
xml.write('</annotation>')
image_files = glob("labelmedataset/images/" + "*.jpg")
print("copy image files to VOC007/JPEGImages/")
for image in image_files:
shutil.copy(image, saved_path + "JPEGImages/")
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")
train_files, val_files = train_test_split(trainval_files, test_size=0.15, random_state=55)
for file in train_files:
ftrain.write(file + "\n")
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()
|