深度学习-json标签转yolo(OBB)格式

代码

import os
import json
import cv2

# 文件夹路径
images_folder = 'images'
labels_folder = 'labels'
output_folder = 'labels_txt'

# 创建输出文件夹
os.makedirs(output_folder, exist_ok=True)

# 获取所有图片文件名(假设图片文件格式为jpg)
image_files = [f for f in os.listdir(images_folder) if f.endswith('.jpg')]

# 处理每一个图片文件和对应的JSON文件
for image_file in image_files:
    # 获取文件前缀名
    file_prefix = os.path.splitext(image_file)[0]

    # 构建图片文件和JSON文件路径
    image_path = os.path.join(images_folder, image_file)
    json_path = os.path.join(labels_folder, f"{file_prefix}.json")

    # 读取图片尺寸
    image = cv2.imread(image_path)
    image_height, image_width, _ = image.shape

    # 读取JSON文件
    with open(json_path, 'r') as file:
        data = json.load(file)

    # 准备YOLO格式的数据
    yolo_data = []

    for shape in data['shapes']:
        label = shape['label']
        if label == "vehicle":
            points = shape['points']
            # 归一化坐标
            normalized_points = []
            for point in points:
                normalized_x = point[0] / image_width
                normalized_y = point[1] / image_height
                normalized_points.extend([normalized_x, normalized_y])

            # YOLO格式:class_index x1 y1 x2 y2 x3 y3 x4 y4
            yolo_data.append(f"0 {' '.join(map(str, normalized_points))}")

    # 写入YOLO格式标签文件
    yolo_file_path = os.path.join(output_folder, f"{file_prefix}.txt")
    with open(yolo_file_path, 'w') as file:
        file.write("\n".join(yolo_data))

print("所有YOLO格式标签文件已生成。")

posted @   梧桐灯下江楚滢  阅读(209)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示