Json转换为txt
生活随笔
收集整理的這篇文章主要介紹了
Json转换为txt
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
注:代碼是以FLIR數(shù)據(jù)集為目的進(jìn)行的編寫,但是也可以使用其它進(jìn)行編寫
from __future__ import print_function import argparse import glob import os import jsonif __name__ == '__main__':# 命令行打印參數(shù)parser = argparse.ArgumentParser()parser.add_argument("path", help='Directory of json files containing annotations') # json文件路徑parser.add_argument("output_path", help='Output directory for image.txt files') # 生成的txt保存路徑args = parser.parse_args()# os.path.join 合并路徑# glob.glob 獲取所有匹配的路徑json_files = sorted(glob.glob(os.path.join(args.path, '*.json'))) # 得到j(luò)son文件路徑下的所有json文件for json_file in json_files:with open(json_file) as f:data = json.load(f) # 將json文件轉(zhuǎn)化為字典images = data['images']annotations = data['annotations']# 圖片w h,為歸一化作準(zhǔn)備width = 640.0height = 512.0for i in range(0, len(images)):converted_results = []for ann in annotations:if ann['image_id'] == i and ann['category_id'] <= 3: # FLIR數(shù)據(jù)集中只有1-3cat_id = int(ann['category_id'])# letf top為左下角坐標(biāo) bbox_width bbox_height為目標(biāo)框長寬# 將bbox數(shù)值轉(zhuǎn)化為float類型left, top, bbox_width, bbox_height = map(float, ann['bbox'])# Yolo的id從0開始,FILIR從1開始cat_id -= 1# 求中心點(diǎn)坐標(biāo)x_center, y_center = (left + bbox_width / 2, top + bbox_height / 2)# 歸一化x_rel, y_rel = (x_center / width, y_center / height)w_rel, h_rel = (bbox_width / width, bbox_height / height)converted_results.append((cat_id, x_rel, y_rel, w_rel, h_rel))image_name = images[i]['file_name']# 這里image_name是thermal_8_bit/FLIR_xxxxx.jpeg格式,我們文件名只需要FLIR_xxxxx部分image_name = image_name[14:-5]print(image_name) # 驗(yàn)證是名稱否正確file = open(args.output_path + str(image_name) + '.txt', 'w+')file.write('\n'.join('%d %.6f %.6f %.6f %.6f' % res for res in converted_results))file.close()運(yùn)行方法:python 代碼文件名稱 json文件路徑 保存文件路徑
假設(shè)py文件名為jsontotxt,
python jsontotxt ./ ./這樣運(yùn)行沒有問題,保存文件路徑可能會存在文件,會把文件夾名字的前綴給修改,按我這樣是完全沒問題的,等有時(shí)間我會修改一下
總結(jié)
以上是生活随笔為你收集整理的Json转换为txt的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: afm原子力分析软件_AFM数据处理软件
- 下一篇: 2022大连理工887软件工程初试