语义分割数据集转YOLOv5数据集
json文件 转txt文件
import json
import os
import os.path
'''
获取图片名称
'''
def image_id(rootdir):
a = []
# root 表示当前正在访问的文件夹路径
# dirnames 表示该文件夹下的子目录名list
# filenames 表示该文件夹下的文件list
for root, dirnames, filenames in os.walk(rootdir):
for filename in filenames:
filename = filename.strip('.json')
a.append(filename)
return a
'''
获取目标检测Bounding_box
'''
def position(pos):
# 该函数用来找出xmin,ymin,xmax,ymax即bbox包围框
x = []
y = []
nums = len(pos)
for i in range(nums):
x.append(pos[i][0])
y.append(pos[i][1])
x_max = max(x)
x_min = min(x)
y_max = max(y)
y_min = min(y)
b = (float(x_min), float(x_max), float(y_min), float(y_max))
return b
'''
归一化处理
'''
def convert(size, box):
# 该函数将xmin,ymin,xmax,ymax转为x,y,w,h中心点坐标和宽高
dw = 1. / (size[0])
dh = 1. / (size[1])
x = (box[0] + box[1]) / 2.0 - 1
y = (box[2] + box[3]) / 2.0 - 1
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
def convert_annotation(rootdir,out_file,image_id):
# json标签的地址
load_f = open(rootdir + '/{0}.json'.format(image_id), 'r')
load_dict = json.load(load_f)
# 输出标签的地址
out_file = open(out_file + '/{0}.txt'.format(image_id), 'w')
# 查询load_dict 字典下键值名
keys=tuple(load_dict.keys())
# print(keys)
# 获取原图的高、宽 用于归一化
w = load_dict['imageWidth']
h = load_dict['imageHeight']
objects = load_dict['shapes']
# object 为数组
# print(objects)
nums = len(objects)
# print(nums)
for i in range(0,nums):
# print(objects[i]['points'])
# print(image_id)
print(image_id + '第{}个'.format(i))
pos = objects[i]['points']
box = position(pos)
# 打印未归一化前的数据 用来检测数据是否正确
print(box)
bb = convert([w , h], box)
# Maize == 0
cls_id = 0
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
if __name__ == '__main__':
# json文件输入目录
rootdir = r'C:\Users\Administrator\Desktop\test\laser_json'
# txt文件输出目录
out_file = r'C:\Users\Administrator\Desktop\test\labels'
# 获取json目录下所有文件名
ids = image_id(rootdir)
for id in ids:
convert_annotation(rootdir,out_file,id)
print(id + '.json' + '已转换')
print('over!')