You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将JSON格式太阳能板数据集标注转为YOLOv8格式?求转换脚本

将JSON标注转换为YOLOv8格式的方案

格式说明

YOLOv8的实例分割(多边形)标注规则:

  • 每个图像对应一个同名的.txt标注文件
  • 每行代表一个目标,格式为:class_id x1 y1 x2 y2 ... xn yn
  • 所有x/y坐标必须是归一化后的值(x除以图像宽度,y除以图像高度)
  • 类别ID从0开始(假设你的太阳能板是唯一类别,可自行修改)

转换脚本

以下是直接可用的Python脚本,适配你提供的JSON标注格式:

import json
import os
from PIL import Image

# 配置参数
JSON_PATH = "your_annotations.json"  # 你的JSON标注文件路径
IMAGE_DIR = "your_images_folder"     # 图像存放文件夹
OUTPUT_DIR = "yolo_annotations"      # 转换后标注的输出文件夹
CLASS_ID = 0                         # 太阳能板的类别ID,按需修改

# 创建输出目录
os.makedirs(OUTPUT_DIR, exist_ok=True)

# 读取JSON标注
with open(JSON_PATH, "r", encoding="utf-8") as f:
    annotations = json.load(f)

# 遍历每个图像的标注
for item in annotations:
    img_name = item["id"]
    # 拼接图像完整路径(假设图像格式为jpg,可根据实际修改为png等)
    img_path = os.path.join(IMAGE_DIR, f"{img_name}.jpg")
    
    # 读取图像宽高,用于坐标归一化
    try:
        with Image.open(img_path) as img:
            width, height = img.size
    except FileNotFoundError:
        print(f"警告:未找到图像 {img_path},跳过该标注")
        continue
    
    # 生成对应标注文件路径
    txt_path = os.path.join(OUTPUT_DIR, f"{img_name}.txt")
    with open(txt_path, "w", encoding="utf-8") as txt_file:
        # 遍历当前图像的所有多边形标注
        for polygon in item["polygons"]:
            points = polygon["points"]
            # 提取x、y坐标并归一化
            normalized_points = []
            for point in points:
                x_norm = point["x"] / width
                y_norm = point["y"] / height
                normalized_points.append(f"{x_norm:.6f}")
                normalized_points.append(f"{y_norm:.6f}")
            # 拼接成YOLO格式的行
            line = f"{CLASS_ID} {' '.join(normalized_points)}\n"
            txt_file.write(line)

print("标注转换完成!")

使用说明

  1. 安装依赖:执行 pip install pillow(如果偏好OpenCV,替换为pip install opencv-python,并修改图像读取部分)
  2. 修改脚本中的配置参数,对应你的实际文件路径和类别ID
  3. 运行脚本,转换后的标注会保存在OUTPUT_DIR指定的文件夹中
  4. 验证:可使用YOLOv8官方库的可视化方法(如ultralytics的show())检查标注是否匹配图像

内容的提问来源于stack exchange,提问作者ginpain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 20:44:52