Json转换为txt

注:代码是以FLIR数据集为目的进行的编写,但是也可以使用其它进行编写

from __future__ import print_function
import argparse
import glob
import os
import json

if __name__ == '__main__':
    # 命令行打印参数
    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')))  # 得到json文件路径下的所有json文件

    for json_file in json_files:
        with open(json_file) as f:
            data = json.load(f)  # 将json文件转化为字典
            images = data['images']
            annotations = data['annotations']

            # 图片w h,为归一化作准备
            width = 640.0
            height = 512.0

            for i in range(0, len(images)):
                converted_results = []
                for ann in annotations:
                    if ann['image_id'] == i and ann['category_id'] <= 3:  # FLIR数据集中只有1-3
                        cat_id = int(ann['category_id'])

                        # letf top为左下角坐标 bbox_width bbox_height为目标框长宽
                        # 将bbox数值转化为float类型
                        left, top, bbox_width, bbox_height = map(float, ann['bbox'])

                        # Yolo的id从0开始,FILIR从1开始
                        cat_id -= 1

                        # 求中心点坐标
                        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)  # 验证是名称否正确

                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()

运行方法:python 代码文件名称 json文件路径 保存文件路径

假设py文件名为jsontotxt

python jsontotxt ./ ./

这样运行没有问题,保存文件路径可能会存在文件,会把文件夹名字的前缀给修改,按我这样是完全没问题的,等有时间我会修改一下

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Fighting_1997

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值