labelme标注的<分割数据集>json转yolo<分割>数据集txt

import json
import os

def convert_labelme_to_yolo(json_file, output_txt_file, label_to_class_id):
    with open(json_file, 'r') as file:
        data = json.load(file)
    
    image_width = data['imageWidth']
    image_height = data['imageHeight']

    with open(output_txt_file, 'w') as file:
        for shape in data['shapes']:
            points = shape['points']
            class_id = label_to_class_id.get(shape['label'], -1)
            normalized_points = []
            for x, y in points:
                nx = round(x / image_width, 6)
                ny = round(y / image_height, 6)
                normalized_points.append(f"{nx} {ny}")
            file.write(f"{class_id} " + " ".join(normalized_points) + "\n")

def batch_convert(json_folder, output_folder, label_to_class_id):
    # 确保输出文件夹存在
    os.makedirs(output_folder, exist_ok=True)
    
    # 遍历文件夹中的所有JSON文件
    for filename in os.listdir(json_folder):
        if filename.endswith('.json'):
            json_file = os.path.join(json_folder, filename)
            output_txt_file = os.path.join(output_folder, filename.replace('.json', '.txt'))
            convert_labelme_to_yolo(json_file, output_txt_file, label_to_class_id)
def create_label_file(label_dict, output_path):
    sorted_labels = [label for label, _ in sorted(label_dict.items(), key=lambda item: item[1])]
    
    with open(output_path, 'w') as file:
        for label in sorted_labels:
            file.write(f"{label}\n")

if __name__ == '__main__':
# 使用示例
    label_to_class_id = {
        'car': 0,
        'dashedline': 1,
        'midlane': 2,
        'pothole': 3,
        'rightlane': 4
    }

    json_folder = r'E:\BaiduNetdiskDownload\网课YOLOv8实例分割训练自己的数据集\mydataset\roadscene_train'
    output_folder = r'E:\BaiduNetdiskDownload\网课YOLOv8实例分割训练自己的数据集\mydataset\roadscene_train'

    batch_convert(json_folder, output_folder, label_to_class_id)
    # 生成lableme.txt文件,按照label_dict的值从小到大排列,一个类别1行
    create_label_file(label_to_class_id,r'C:\xxx\yolo-label.txt')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值