json文件转换为.txt格式(可运行,检测任务用)

import json
import os

# 定义标签映射
label_map = {
    "background": 0,
    "di": 1
}

def convert_labelme_to_yolo(json_path, output_dir):
    try:
        with open(json_path, 'r', encoding='utf-8') as f:
            labelme_data = json.load(f)

        image_width = labelme_data['imageWidth']
        image_height = labelme_data['imageHeight']

        yolo_annotations = []
        for shape in labelme_data['shapes']:
            label = shape['label']
            if label not in label_map:
                continue  # 忽略未定义的标签

            class_id = label_map[label]
            points = shape['points']

            if shape['shape_type'] == 'rectangle':
                (x1, y1), (x2, y2) = points
            elif shape['shape_type'] == 'polygon':
                x1, y1 = min(point[0] for point in points), min(point[1] for point in points)
                x2, y2 = max(point[0] for point in points), max(point[1] for point in points)
            elif shape['shape_type'] == 'circle':
                # YOLO不直接支持圆形,转为最小外接矩形
                (x_center, y_center), (x_radius, _) = points
                x1 = x_center - x_radius
                y1 = y_center - x_radius
                x2 = x_center + x_radius
                y2 = y_center + x_radius
            elif shape['shape_type'] == 'line':
                # 线条转为最小矩形框,便于YOLO处理
                x1, y1 = min(point[0] for point in points), min(point[1] for point in points)
                x2, y2 = max(point[0] for point in points), max(point[1] for point in points)
            else:
                continue  # 其他类型不处理

            # 归一化并计算中心坐标和宽高
            x_center = (x1 + x2) / 2.0 / image_width
            y_center = (y1 + y2) / 2.0 / image_height
            width = (x2 - x1) / image_width
            height = (y2 - y1) / image_height

            # 保存YOLO格式标注
            yolo_annotations.append(f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}")

        # 输出到txt文件
        output_file = os.path.join(output_dir, os.path.splitext(os.path.basename(json_path))[0] + '.txt')
        with open(output_file, 'w') as f:
            f.write('\n'.join(yolo_annotations))

        print(f"Successfully converted: {json_path}")

    except Exception as e:
        print(f"Error processing {json_path}: {e}")

def process_folder(input_folder, output_folder):
    # 创建输出文件夹(如果不存在)
    os.makedirs(output_folder, exist_ok=True)

    # 处理输入文件夹中的每个 JSON 文件
    for filename in os.listdir(input_folder):
        if filename.endswith(".json"):
            json_path = os.path.join(input_folder, filename)
            convert_labelme_to_yolo(json_path, output_folder)

#  修改成自己的地址
input_folder = "D:\LanKao\HuiAnjson\yifengjson"     # labelme标注的json标签文件地址
output_folder = "D:/LanKao/HuiAnjson/YiFengyolo_labels"   # 转换为yolo模型需要的数据集格式

process_folder(input_folder, output_folder)

# 列出输出文件夹中的文件以确认
output_files = os.listdir(output_folder)
print("Generated YOLO label files:", output_files)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值