voc转coco或labelme转coco点这里:
将voc数据集xml格式、labelme标注转为coco数据集json格式
由于之前使用Mask R-CNN数据集是coco格式的,现在用YOLO需要voc格式的数据集,重新制作样本太麻烦,所以直接用python代码转换。
1.首先要把一个整的json文件分为单个的,因为我的coco数据集是把全部标签整合到一个文件的
(如果本来就是单个单个的json文件,可以直接转到第二步格式转换)
我的数据集较小,所以是一次一次提取的,如果数据集较大的话可以自己改成循环。
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 更加美观显示
循环版本:
from __future__ import print_function
import json
json_file='F:/研究生/研一/计算机视觉/遥感影像数据集/COCO/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']
for i in range(234): # 一共234张图片
data_2['images']=[data['images'][i]] # 只提取第i张图片
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文件,便于查看数据特点
savepath = 'F:/研究生/研一/计算机视觉/遥感影像数据集/COCO/single/' + str(imgID).zfill(6) + '.json'
json.dump(data_2,open(savepath,'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('<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')# 是否用于分割(在图像物体识别中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('\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')# 是否被截断(0表示完整)
xml.write('\t\t<difficult>0</difficult>\n')# 目标是否难以识别(0表示容易识别)
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>')
# 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()