labelme 标注矩形检测数据格式转 VOC 数据集格式
声明:本文章仅因个人工作学习过程中需要频繁转换格式,手写了转换代码,方便个人使用,开源只为有需要的人提供方便。如有疑问请联系:zhuchaojie@buaa.edu.cn
目标检测开源工具 labelme:Labelme
针对检测标注数据:(矩形框)
1. labelme 数据格式
注:如果图片格式不是 .jpg
请修改
data
- 00001.jpg
- 00001.json
- 00002.jpg
- 00002.json
2. VOC2007数据格式
VOC2007/
- Annotations/
- JPEGImages/
ImageSets/
Main/
- train.txt
- val.txt
- trainval.txt
- test.txt
3. 转换代码
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.标签路径
labelme_path = "./labelme/" #原始labelme标注数据路径
saved_path = "./VOC2007/" #保存路径
#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.split("/")[-1].split(".json")[0] for i in 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(labelme_path + 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>' + 'UAV_data' + '</folder>\n')
xml.write('\t<filename>' + json_file_ + ".jpg" + '</filename>\n')
xml.write('\t<source>\n')
xml.write('\t\t<database>The UAV autolanding</database>\n')
xml.write('\t\t<annotation>UAV AutoLanding</annotation>\n')
xml.write('\t\t<image>flickr</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>ChaojieZhu</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')
for multi in json_file["shapes"]:
points = np.array(multi["points"])
xmin = min(points[:,0])
xmax = max(points[:,0])
ymin = min(points[:,1])
ymax = max(points[:,1])
label = multi["label"]
if xmax <= xmin:
pass
elif ymax <= ymin:
pass
else:
xml.write('\t<object>\n')
xml.write('\t\t<name>'+"bubble"+'</name>\n')
xml.write('\t\t<pose>Unspecified</pose>\n')
xml.write('\t\t<truncated>1</truncated>\n')
xml.write('\t\t<difficult>0</difficult>\n')
xml.write('\t\t<bndbox>\n')
xml.write('\t\t\t<xmin>' + str(xmin) + '</xmin>\n')
xml.write('\t\t\t<ymin>' + str(ymin) + '</ymin>\n')
xml.write('\t\t\t<xmax>' + str(xmax) + '</xmax>\n')
xml.write('\t\t\t<ymax>' + str(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(labelme_path + "*.jpg")
print("copy image files to VOC007/JPEGImages/")
for image in image_files:
shutil.copy(image,saved_path +"JPEGImages/")
#6.split files for txt
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.split("/")[-1].split(".xml")[0] for i in total_files]
#test_filepath = ""
for file in total_files:
ftrainval.write(file + "\n")
#test
#for file in os.listdir(test_filepath):
# ftest.write(file.split(".jpg")[0] + "\n")
#split
train_files,val_files = train_test_split(total_files,test_size=0.15,random_state=42)
#train
for file in train_files:
ftrain.write(file + "\n")
#val
for file in val_files:
fval.write(file + "\n")
ftrainval.close()
ftrain.close()
fval.close()
#ftest.close()
注:
- 训练集和验证集的划分方法是采用
sklearn.model_selection.train_test_split
进行分割的。 - 默认图片格式
.jpg
,如果图片格式有变化,请自行修改代码中的.jpg
名称。 - 默认不添加测试集,如果有需要,自行解开注释即可。
TODO
- labelme 转 coco
- voc 转 coco
- coco 转 voc
- 分割任务
ValueError: With n_samples=0, test_size=0.15 and train_size=None, the resulting train set will be empty. Adjust any of the aforementioned parameters
博主,您好!我运行代码后能成功创建文件夹,但会报上面这个错,您知道为啥吗?十分感谢您的解答!
这种一般是某个类别的数量较少
嘿,兄弟,你的问题解决了没?我也 遇到了同样的问题。
博主,你好,我也遇到了这个问题,我的类别一个是200张,一个是300张,请问如何解决呀
这个我这边没遇到过,建议谷歌一下或者百度一下
我把test_size的数值改大了一点就可以了
89行改成 total_files = glob(saved_path + "Annotations/*.xml") 就可以了
如果你是Windows环境下,把第23行“/”换为“\\”可能会起作用。还有要注意标签路径要写对
你好,想问一下,这个代码是不是只能解决在labelme中标注时只有标准的矩形情况。
是的,因为这些都是做的目标检测,对于分割的暂时还没做,另外如果图像中没有目标的话,一般这种图不做训练。
谢谢博主
博主您好,我在运行代码后能成功创建文件夹,但文件夹内为空,标注的图片和.json都以000001.jpg,000001.json...这样的格式命名,也没有报错,希望能够得到您的帮助,非常感谢!
如果图片名和json名对应上的话应该不会出问题,你这种情况我也没遇到过,你debug一下看看是不是没有读取到标注。
好的,谢谢啦
博主,您好!能不能请教一下如果标注是多边形框应该怎么将json文件转换成xml文件呢?
ValueError: With n_samples=0, test_size=0.15 and train_size=None, the resulting train set will be empty. Adjust any of the aforementioned parameters
博主,您好,出现这样的错误如何解决呀
博主,您好,请问image格式是否有限制?image是label图片还是没有标记过的图片?label是生成的json文件嘛?
没有限制,请参考labelme的格式。
你好,FileNotFoundError: [Errno 2] No such file or directory: 'datasets/labelme/labelme\\1.json'错误
name都是bubble...@(汗)
改成label就好了以及路径名称处理有点小问题
22行改成
files = [i.split("/labelme")[-1].split(".json")[0] for i in files]
就跑通了
注意63行,把“bubble”换成label
代码写得真傻逼啊