lableme的 json (矩形框标注)转换为yolo 格式的txt --- (类别 x,y,w,h形式)

import json
import os

def convert_labelme_to_yolo(json_path, txt_path, label_dict):
    with open(json_path, 'r') as file:
        data = json.load(file)

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

    with open(txt_path, 'w') as file:
        for shape in data['shapes']:
            label = shape['label']
            points = shape['points']
            x_min, y_min = points[0]
            x_max, y_max = points[1]

            x_center = (x_min + x_max) / 2 / image_width
            y_center = (y_min + y_max) / 2 / image_height
            width = (x_max - x_min) / image_width
            height = (y_max - y_min) / image_height

            class_id = label_dict[label]
            file.write(f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n")

def batch_convert(input_folder, output_folder, label_dict):
    os.makedirs(output_folder, exist_ok=True)
    for file_name in os.listdir(input_folder):
        if file_name.endswith('.json'):
            json_path = os.path.join(input_folder, file_name)
            txt_path = os.path.join(output_folder, file_name.replace('.json', '.txt'))
            convert_labelme_to_yolo(json_path, txt_path, label_dict)

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__':
    # Example usage
    label_dict = {"car": 0, "tree": 1}
    input_folder = r'C:\Users\ailiu\Desktop\yolo\data'
    output_folder = r'C:\Users\ailiu\Desktop\yolo\data'
    batch_convert(input_folder, output_folder, label_dict)
    # 生成lableme.txt文件,按照label_dict的值从小到大排列,一个类别1行
    create_label_file(label_dict,r'C:\Users\ailiu\Desktop\yolo\data\yolo-label.txt')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值