目标检测算法之数据集标签格式转换:json2txt、xml2txt
目标检测最常见的模型:YOLO,常见的几种标注方式:矩形框、旋转矩形框、实例分割中的多边形标注等类型,根据其标注标签,目标检测主要有以下两种转换方式:
- 通过labelme标注的矩形框标签为
.json
格式 - > yolo模型需要的.txt
格式
- 通过labelimg标注的矩形框标签为
.xml
格式 -> yolo模型需要的.txt
格式
下边详细给出转换demo:
1. json2txt
- labelme安装
pip labelme
pip pyqt5
标注:鼠标在图像上右键选择create Rectangle
即可创建矩形框进行标注
- 下边是将
.json
标签文件转换为.txt格式demo:
# 处理labelme多边形矩阵的标注 json转化txt
import json
import os
name2id = {'peanuthull': 0, 'kernel': 1}
def convert(img_size, box):
dw = 1. / (img_size[0])
dh = 1. / (img_size[1])
x = (box[0] + box[2]) / 2.0
y = (box[1] + box[3]) / 2.0
w = abs(box[2] - box[0])
h = abs(box[3] - box[1])
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
def decode_json(json_floder_path, txt_outer_path, json_name):
# json_floder_path='E:\\Python_package\\itesjson\\'
# json_name='V1125.json'
txt_name = txt_outer_path + json_name[:-5] + '.txt'
with open(txt_name, 'w') as f:
json_path = os.path.join(json_floder_path, json_name) # os路径融合
data = json.load(open(json_path, 'r', encoding='gb2312', errors='ignore'))
img_w = data['imageWidth'] # 图片的高
img_h = data['imageHeight'] # 图片的宽
isshape_type = data['shapes'][0]['shape_type']
print(isshape_type)
# print(isshape_type)
# print('下方判断根据这里的值可以设置为你自己的类型,我这里是polygon'多边形)
# len(data['shapes'])
for i in data['shapes']:
label_name = i['label'] # 得到json中你标记的类名
if (i['shape_type'] == 'polygon'): # 数据类型为多边形 需要转化为矩形
x_max = 0
y_max = 0
x_min = 100000
y_min = 100000
for lk in range(len(i['points'])):
x1 = float(i['points'][lk][0])
y1 = float(i['points'][lk][1])
# print(x1)
if x_max < x1:
x_max = x1
if y_max < y1:
y_max = y1
if y_min > y1:
y_min = y1
if x_min > x1:
x_min = x1
bb = (x_min, y_max, x_max, y_min)
if (i['shape_type'] == 'rectangle'): # 为矩形不需要转换
x1 = float(i['points'][0][0])
y1 = float(i['points'][0][1])
x2 = float(i['points'][1][0])
y2 = float(i['points'][1][1])
bb = (x1, y1, x2, y2)
bbox = convert((img_w, img_h), bb)
try:
f.write(str(name2id[label_name]) + " " + " ".join([str(a) for a in bbox]) + '\n')
except:
pass
if __name__ == "__main__":
json_floder_path = 'data_\\jsons\\' # 存放json的文件夹的绝对路径
txt_outer_path = 'data_\\txts\\' # 存放txt的文件夹绝对路径
json_names = os.listdir(json_floder_path)
print("共有:{}个文件待转化".format(len(json_names)))
flagcount = 0
for json_name in json_names:
decode_json(json_floder_path, txt_outer_path, json_name)
flagcount += 1
print("还剩下{}个文件未转化".format(len(json_names) - flagcount))
# break
print('转化全部完毕')
2. xml2txt
- labelimg安装
pip labelimg
pip pyqt5
- 标注:左键选择
create RectBox
即可拉框标注
- 下边给出
.xml
转为.txt
的demo:
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
def convert(size, box):
x_center = (box[0] + box[1]) / 2.0
y_center = (box[2] + box[3]) / 2.0
x = x_center / size[0]
y = y_center / size[1]
w = (box[1] - box[0]) / size[0]
h = (box[3] - box[2]) / size[1]
return (x, y, w, h)
def convert_annotation(xml_files_path, save_txt_files_path, classes):
xml_files = os.listdir(xml_files_path)
print(xml_files)
for xml_name in xml_files:
print(xml_name)
xml_file = os.path.join(xml_files_path, xml_name)
out_txt_path = os.path.join(save_txt_files_path, xml_name.split('.')[0] + '.txt')
out_txt_f = open(out_txt_path, 'w')
tree = ET.parse(xml_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
for obj in root.iter('object'):
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in classes or int(difficult) == 1:
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
float(xmlbox.find('ymax').text))
# b=(xmin, xmax, ymin, ymax)
print(w, h, b)
bb = convert((w, h), b)
out_txt_f.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
if __name__ == "__main__":
classes = ['person', 'face','hand','garb','larwas','conwas','foowas','recyc'] #8类
# 1、voc格式的xml标签文件路径
xml_files1 = r'F:\Deeplearning\yolov5-master\mytrain\xmls'
# 2、转化为yolo格式的txt标签文件存储路径
save_txt_files1 = r'F:\Deeplearning\yolov5-master\mytrain\labels'
convert_annotation(xml_files1, save_txt_files1, classes)