首先json格式如下
不是该格式可以退出本博客
转化代码如下
import json
import os
classify_map = {
'goose': 0,
}
def xyxy2xywh(size, box):
dw = 1. / size[0]
dh = 1. / size[1]
x = (box[0] + box[2]) / 2 * dw
y = (box[1] + box[3]) / 2 * dh
w = (box[2] - box[0]) * dw
h = (box[3] - box[1]) * dh
return (x, y, w, h) # 返回的都是标准化后的值
def voc2yolo(path):
txt_out_path = r'E:\dataset\labels\test' # 转换后txt保存路径
for file in os.listdir(path):
print(file)
with open(os.path.join(path, file), 'r') as f:
data = json.load(f)
txt_name = file.split(".")[0] + ".txt"
h = data['imageHeight']
w = data['imageWidth']
res = []
for item in data['shapes']:
classify = classify_map[item['label']]
points = item['points']
xmin = min(points[0][0], points[1][0])
ymin = min(points[0][1], points[1][1])
xmax = max(points[0][0], points[1][0])
ymax = max(points[0][1], points[1][1])
box = [float(xmin), float(ymin), float(xmax),
float(ymax)]
# # 将x1, y1, x2, y2转换成yolov5所需要的x, y, w, h格式
bbox = xyxy2xywh((w, h), box)
res.append([classify,bbox])
# # 写入目标文件中,格式为 id x y w h
with open(os.path.join(txt_out_path, txt_name), 'w') as out_file:
for classify, bbox in res:
out_file.write(str(classify) + " " + " ".join(str(x) for x in bbox) + '\n')
out_file.close()
if __name__ == '__main__':
# json格式数据路径
path = r'E:\dataset\json\test'
voc2yolo(path)
需要修改txt_out_path,path,classify_map
有问题可以在评论区询问,看到会回复