json文件批量转为txt文件
1 批量json标注文件:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3b9a4ddd445602cb69431cbea7a05f38.png)
2 json所对应的各个图片:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4c65463515f64b344b9c5467404d998c.png)
3 每个json文件内容:
[
{
"type": 1,
"x": 1168,
"y": 639,
"width": 457,
"height": 245,
"segmentation": []
},
{
"type": 1,
"x": 831,
"y": 626,
"width": 77,
"height": 57,
"segmentation": []
},
{
"type": 1,
"x": 810,
"y": 627,
"width": 36,
"height": 48,
"segmentation": []
},
{
"type": 2,
"x": 753,
"y": 628,
"width": 44,
"height": 52,
"segmentation": []
},
{
"type": 1,
"x": 615,
"y": 619,
"width": 31,
"height": 22,
"segmentation": []
}
]
4 代码转换(python)
import os
import json
from PIL import Image
json_dir = 'D:/train/label_json' # json文件路径
out_dir = 'D:/train/label_txt/' # 输出的 txt 文件路径
def get_json(json_file, filename):
# 读取 json 文件数据
with open(json_file, 'r') as load_f:
content = json.load(load_f)
file_path = 'D:/train/image/'+filename+'.jpg' # 每个json文件对应的图片文件路径
img = Image.open(file_path)
# imgSize = img.size # 大小/尺寸
image_width = img.width # 图片的宽
image_height = img.height # 图片的高
filename_txt = out_dir + filename+'.txt'
# 创建txt文件
fp = open(filename_txt, mode="w", encoding="utf-8")
# 将数据写入文件
#fp.close()
for t in content:
if(t['type']<=7):
# 计算 yolo 数据格式所需要的中心点的 相对 x, y 坐标, w,h 的值
x = (t['x'] + t['width']/ 2) / image_width #归一化
y = (t['y']+ t['height']/ 2 )/ image_height #归一化
w = t['width']/ image_width #归一化
h = t['height'] / image_height #归一化
fp = open(filename_txt, mode="r+", encoding="utf-8")
file_str = str(t['type']-1) + ' ' + str(round(x, 6)) + ' ' + str(round(y, 6)) + ' ' + str(round(w, 6)) + \
' ' + str(round(h, 6))
line_data = fp.readlines()
if len(line_data) != 0:
fp.write('\n' + file_str)
else:
fp.write(file_str)
fp.close()
def main():
files = os.listdir(json_dir) # 得到文件夹下的所有文件名称
s = []
for file in files: # 遍历文件夹
filename = file.split('.')[0]
get_json(json_dir+'/'+file, filename)
if __name__ == '__main__':
main()
5 转换成功后txt文件:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/29507e9e8008a0bdf123d248aeeda783.png)
6 转换成功后txt文件内容:
0 0.727344 0.705093 0.238021 0.226852
0 0.452865 0.606019 0.040104 0.052778
0 0.43125 0.602778 0.01875 0.044444
1 0.403646 0.605556 0.022917 0.048148
0 0.328385 0.583333 0.016146 0.02037