目标检测yolov5:json文件转TXT

输入:

输出;

相关代码:

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)

:注意事项:

### 将 Labelme JSON 文件换为 YOLOv8 支持的 TXT 格式 为了将 Labelme 工具生成的 JSON 数据文件换为适用于 YOLOv8 训练所需的 TXT 格式的标注文件,可以按照以下方法实现: #### 换逻辑说明 YOLOv8 使用一种简单的文本格式存储每个图像的标注数据。对于每张图片,都需要创建一个对应的 `.txt` 文件,其命名应与图片名称一致(仅扩展名不同)。如果某张图片没有任何对象,则无需为其生成 `.txt` 文件。 在 `.txt` 文件中,每一行表示一个边界框,遵循如下格式: ``` <class_id> <x_center_normalized> <y_center_normalized> <width_normalized> <height_normalized> ``` 其中: - `<class_id>` 是类别索引; - `<x_center_normalized>` 和 `<y_center_normalized>` 表示边界框中心点相对于整个图像宽度和高度的比例坐标; - `<width_normalized>` 和 `<height_normalized>` 则分别代表边界框宽高占整幅图比例[^1]。 而 Labelme 输出的是基于像素坐标的多边形顶点列表形式的数据结构。因此需要先解析该 JSON 文件中的 shape 信息,并将其化为矩形区域再进一步标准化处理成上述提到的形式以便于后续模型读取使用[^2]。 以下是具体实现代码: ```python import os import json from PIL import Image def convert_labelme_to_yolo(json_file, output_dir, class_list): """ Convert labelme JSON annotations into YOLO txt files. Args: json_file (str): Path of the input JSON file. output_dir (str): Directory where to save generated .txt files. class_list (list): List containing all possible classes as strings. """ # Load data from given path with open(json_file) as f: data = json.load(f) img_path = os.path.join(os.path.dirname(json_file), data['imagePath']) try: im = Image.open(img_path) except FileNotFoundError: print(f"Image {img_path} not found.") return width, height = im.size yolo_annotations = [] shapes = data.get('shapes', []) for shape in shapes: points = shape["points"] # Calculate bounding box coordinates based on polygon vertices min_x = min([p[0] for p in points]) max_x = max([p[0] for p in points]) min_y = min([p[1] for p in points]) max_y = max([p[1] for p in points]) x_center = ((min_x + max_x)/2) / width y_center = ((min_y + max_y)/2) / height w_norm = abs(max_x - min_x) / width h_norm = abs(max_y - min_y) / height cls_name = shape["label"] if cls_name not in class_list: continue cls_idx = class_list.index(cls_name) line = f"{cls_idx} {x_center:.6f} {y_center:.6f} {w_norm:.6f} {h_norm:.6f}" yolo_annotations.append(line) base_filename = os.path.splitext(data['imagePath'])[0] out_txt_filepath = os.path.join(output_dir, f"{base_filename}.txt") with open(out_txt_filepath, 'w') as wf: wf.write("\n".join(yolo_annotations)) # Example usage: json_directory = '/path/to/json/files' output_directory = '/desired/output/path' classes = ['cat', 'dog'] for filename in os.listdir(json_directory): if filename.endswith('.json'): filepath = os.path.join(json_directory, filename) convert_labelme_to_yolo(filepath, output_directory, classes) ``` 此脚本会遍历指定目录下的所有 `*.json` 文件并逐一完成化操作,最终把结果保存至另一设定好的输出路径下。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值