目标检测yolov5:json文件转TXT

输入:

目标检测yolov5:json文件转TXT_第1张图片

目标检测yolov5:json文件转TXT_第2张图片

输出;

目标检测yolov5:json文件转TXT_第3张图片目标检测yolov5:json文件转TXT_第4张图片

相关代码:

import os
import json
class BDD_to_YOLOv5:
    def __init__(self):
        self.writepath = r"C:\Users\Wu\Desktop\cv test\\"

        #-----------------------------------------------------------#
        #self.writepath 保存最后生成的所有txt文件的地址 注意格式!!!r"C:\Users\Wu\Desktop\cv test\\"
        # -----------------------------------------------------------#


        self.bdd100k_width_ratio = 1.0/1920
        self.bdd100k_height_ratio = 1.0/1080
        self.select_categorys = ["pedestrian", "motor-vehicle", "non-motor-vehicle"]
        self.categorys_nums = {
            "pedestrian":0,
            "motor-vehicle":1,
            "non-motor-vehicle":2}
    def bdd_to_yolov5(self, path):
        lines = ""
        with open(path) as fp:
            j = json.load(fp)
            write = open(self.writepath + "%s.txt" % j["info"]["image_name"].split(".")[0], 'w')
            for fr in j["annotations"]:
                if fr["category_id"] in self.select_categorys:
                    temp_category = fr["category_id"]
                    idx = self.categorys_nums[temp_category]
                    cx = fr["bbox"][0] + fr["bbox"][2] / 2.0
                    cy = fr["bbox"][1] + fr["bbox"][3]/ 2.0
                    w = fr["bbox"][2]
                    h = fr["bbox"][3]
                    if w <= 0 or h <= 0:
                        continue
                    # 根据图片尺寸进行归一化
                    cx, cy, w, h = cx * self.bdd100k_width_ratio, cy * self.bdd100k_height_ratio, w * self.bdd100k_width_ratio, h * self.bdd100k_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 = r"C:\Users\Wu\Desktop\cv test\cv test\label"
    #给的label对应文件夹地址
    #-----------------------------------------------------------#


    bdd_labels_dir = r"C:\Users\Wu\Desktop\cv test\cv test\label"
    fileList = os.listdir(bdd_labels_dir)

    #-----------------------------------------------------------#
    #遍历label文件夹下的json文件
    #-----------------------------------------------------------#
    obj = BDD_to_YOLOv5()
    for path in fileList:
        filepath = os.path.join(bdd_labels_dir,path)
        print(path)
        obj.bdd_to_yolov5(filepath)

:注意事项:

目标检测yolov5:json文件转TXT_第5张图片目标检测yolov5:json文件转TXT_第6张图片

你可能感兴趣的:(学习,中介者模式,建造者模式)