import json
import os
import cv2
import shutil
import math

# 输入文件夹
json_folder = r"\\192.168.50.222\share\zyh\data\via\via_json"
image_folder = r"\\192.168.50.222\share\zqy\colorphoto_for_guanban"
output_folder = r"\\192.168.50.222\share\zyh\data\rgb_tuoyuan_draw"
os.makedirs(output_folder, exist_ok=True)

for json_file in os.listdir(json_folder):
    if not json_file.lower().endswith(".json"):
        continue

    json_path = os.path.join(json_folder, json_file)

    with open(json_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    img_metadata = data.get("_via_img_metadata", {})

    for img_info in img_metadata.values():
        filename = img_info.get("filename")
        regions = img_info.get("regions", [])

        # 提取椭圆
        ellipses = [r for r in regions if r.get("shape_attributes", {}).get("name") == "ellipse"]
        if not ellipses:
            continue

        # 找图片路径
        img_path = os.path.join(image_folder, filename)
        if not os.path.exists(img_path):
            print(f"图片未找到: {filename}")
            continue

        img = cv2.imread(img_path)
        if img is None:
            print(f"图片无法读取: {filename}")
            continue

        # 绘制椭圆
        for e in ellipses:
            cx = e["shape_attributes"]["cx"]
            cy = e["shape_attributes"]["cy"]
            rx = e["shape_attributes"]["rx"]
            ry = e["shape_attributes"]["ry"]
            theta = e["shape_attributes"].get("theta", 0)  # 弧度

            # OpenCV ellipse 角度需要度数，顺时针
            angle_deg = -math.degrees(theta)
            center = (int(cx), int(cy))
            axes = (int(rx), int(ry))

            cv2.ellipse(img, center, axes, angle_deg, 0, 360, (0, 255, 0), 2)

        # 保存画好的图片
        img_output_path = os.path.join(output_folder, filename)
        cv2.imwrite(img_output_path, img)

        print(f"已生成带椭圆标注的图片: {img_output_path}")
