如今,深度学习非常热门,制作数据集是深度学习很重要的一环。制作数据集就离不开打标签,我们打出来的标签可能是 txt 格式 或者 xml 格式 或者json格式,但是yolo运行的标签格式是txt格式
所以我们要将json格式转换为txt格式 这个转换代码生成的txt文件是归一化后的,非常便捷
以下代码就可以轻松将json格式转换为txt格式。
首先看一下json内容
注意 这个json文件中的 shape_type:rectangle 代表这个打标签方式是矩形框
代码中有注释 修改两个文件路径 一个是json的文件路径 一个是生成txt的文件路径
还要修改一下标签的分类 点击运行 就可以转换了
import json
import os
def convert(img_size, box):
# dw = 1. / (img_size[0])
# dh = 1. / (img_size[1])
# x = (box[0] + box[2]) / 2.0 - 1
# y = (box[1] + box[3]) / 2.0 - 1
# w = box[2] - box[0]
# h = box[3] - box[1]
# x = x * dw
# w = w * dw
# y = y * dh
# h = h * dh
x1 = box[0]
y1 = box[1]
x2 = box[2]
y2 = box[3]
return (x1, y1, x2, y2)
def decode_json(json_floder_path, json_name):
txt_name = 'D:/2021大创/label2/' + json_name[0:-5] + '.txt' #生成txt文件你想存放的路径
txt_file = open(txt_name, 'w')
json_path = os.path.join(json_floder_path, json_name)
data = json.load(open(json_path, 'r', encoding='utf-8'))
img_w = data['imageWidth']
img_h = data['imageHeight']
for i in data['shapes']:
if (i['shape_type'] == 'rectangle' and i['label'] == 'cone tank'): #分类的标签
x1 = float((i['points'][0][0]))/img_w
y1 = float((i['points'][0][1]))/img_h
x2 = float((i['points'][1][0]))/img_w
y2 = float((i['points'][1][1]))/img_h
bb = (x1, y1, x2, y2)
bbox = convert((img_w, img_h), bb)
txt_file.write( '0' + " " + " ".join([str(a) for a in bbox]) + '\n')
if (i['shape_type'] == 'rectangle' and i['label'] == 'water horse bucket'): #分类的标签
x1 = float((i['points'][0][0]))/img_w
y1 = float((i['points'][0][1]))/img_h
x2 = float((i['points'][1][0]))/img_w
y2 = float((i['points'][1][1]))/img_h
bb = (x1, y1, x2, y2)
bbox = convert((img_w, img_h), bb)
txt_file.write( '1' + " " + " ".join([str(a) for a in bbox]) + '\n')
if __name__ == "__main__":
json_floder_path = 'D:/2021大创/label/' #json文件的路径
json_names = os.listdir(json_floder_path)
for json_name in json_names:
decode_json(json_floder_path, json_name)
最后 让我们一起看一下生成的txt文件内容 非常完美!
如果觉得对你有用的话,动动发财的小手点点点赞和关注吧!嘿嘿