json提取内容转化为txt格式

想将json文件转化为txt文件,表示需要帮助
红绿灯那里不用关注,不用识别

img

img

import os
import json
print('')
class BDD_to_YOLOv5:

def __init__(self):
    self.writepath = "yusaidate/json-txt/json labels"
    self.width_ratio = 1.0/1920
    self.height_ratio = 1.0/1020
    self.select_categorys = ["轿车", "suv", "大客车", "大货车", "小货车", "面包车","专业作业车", "微型车", "自行车", "电动/摩托车", '人力三轮车', '电动三轮车']
    self.categorys_nums = {
        "轿车": 0,
        "suv": 1,
        "大客车": 2,
        "大货车": 3,
        "小货车": 4,
        "面包车": 5,
        "专业作业车": 6,
        "微型车": 7,
        "自行车": 8,
        "电动/摩托车": 9,
        "人力三轮车": 10,
        "电动三轮车": 11,

    }

    def bdd_to_yolov5(self, path):
        lines = ""
        with open('yusaidate/json-txt/json labels') as fp:
            j = json.load(fp)
            write = open(self.writepath + "%s.txt" % j["name"], 'w')
            for fr in j["frames"]:
                for objs in fr["objects"]:
                    if objs["category"] in self.select_categorys:
                        temp_category = objs["category"]

                        idx = self.categorys_nums[temp_category]
                        cx = (objs["box2d"]["0"] + objs["box2d"]["2"]) / 2.0
                        cy = (objs["box2d"]["1"] + objs["box2d"]["3"]) / 2.0
                        w = objs["box2d"]["2"] - objs["box2d"]["0"]
                        h = objs["box2d"]["3"] - objs["box2d"]["1"]
                        if w <= 0 or h <= 0:
                                continue
                            # 根据图片尺寸进行归一化
                        cx, cy, w, h = cx * self.width_ratio, cy * self.height_ratio, w * self.width_ratio, h * self.height_ratio
                        line = f"{idx} {cx:.6f} {cy:.6f} {w:.6f} {h:.6f}\n"
                        lines += line

                        if len(lines) != 0:
                            write.writelines(lines)
                            write.close()
                            print("%s has been dealt!" % j["name"])

    if __name__ == "__main__":
        bdd_labels_dir = "yusaidate/json-txt/txt-labels"
        fileList = os.listdir(bdd_labels_dir)
        obj = BDD_to_YOLOv5()
        for path in fileList:
            filepath = bdd_labels_dir + path
            print(path)
            obj.bdd_to_yolov5(filepath)