python_json转yolo文件

发布于:2025-02-12 ⋅ 阅读:(16) ⋅ 点赞:(0)

文章内容
将labelme的内容转换成yolo需要的txt文件

import json
import os
import shutil
import random

# Convert label to idx
# with open("labels.txt", "r") as f:
#     classes = [c.strip() for c in f.readlines()]
#     idx_dict = {c: str(i) for i, c in enumerate(classes)}

# 传入3个路径
# 获取名称,通过名称和路径来确定生成的地址
def onefile_labelme_to_yolo(json_path,txt_path,img_path):
    # 检查输入的路径是否为有效的文件夹路径
    if os.path.isdir(json_path):
        # 遍历文件夹中的所有文件和文件夹
        for root, dirs, files in os.walk(json_path):
            for file in files:
                # 分离文件名和扩展名
                file_name, file_extension = os.path.splitext(file)
                # 生成xml文件路径
                txt_file = os.path.join(txt_path, file_name + '.txt')
                json_file = os.path.join(json_path, file)
                print(txt_file)
                # 读取json文件
                with open(json_file, 'r') as f:
                    labelme_data = json.load(f)
                # 解析json文件
                image_filename = labelme_data["imagePath"]
                image_width = labelme_data["imageWidth"]
                image_height = labelme_data["imageHeight"]

                with open(txt_file, 'w') as f:
                    for shape in labelme_data["shapes"]:
                        label = shape["label"]
                        points = shape["points"]
                        x_min, y_min = points[0]
                        x_max, y_max = points[1]

                        center_x = round(((x_min + x_max) / 2) / image_width, 2)
                        center_y = round(((y_min + y_max) / 2) / image_height, 2)
                        width = round(abs(x_min - x_max) / image_width, 2)
                        height = round(abs(y_min - y_max) / image_height, 2)

                        # class_id = label_dict[label]
                        f.write(f"{0}  {center_x:.6f} {center_y:.6f} {width} {height}\n")

                print(f"Converted {file} to {txt_path}")
    else:
        print(f"{json_path} 不是一个有效的文件夹路径。")



if __name__ == '__main__':
    labelme_folder = "G:\\2025_study\\json"  # labelme生成的标注文件所在的文件夹
    txt_folder = "G:\\2025_study\\txt"  # 存储yolo标注文件的文件夹
    img_folder = "G:\\2025_study\\img"
    onefile_labelme_to_yolo(labelme_folder,txt_folder,img_folder)