import os
import json
import cv2
import numpy as np

input_folder = r"G:\python_ws_g\data\manycircle"
output_folder = r"G:\python_ws_g\data\arcshow"

MAX_WIDTH = 1280
MAX_HEIGHT = 720

def resize_to_fit(image, max_width=MAX_WIDTH, max_height=MAX_HEIGHT):
    h, w = image.shape[:2]
    scale = min(max_width / w, max_height / h, 1.0)
    new_size = (int(w * scale), int(h * scale))
    resized_image = cv2.resize(image, new_size, interpolation=cv2.INTER_NEAREST)  # 改成最近邻防止圆点模糊
    return resized_image

def fit_circle(points):
    """最小二乘法拟合圆: 返回 (cx, cy, r)"""
    x = points[:, 0]
    y = points[:, 1]
    A = np.c_[2*x, 2*y, np.ones(len(points))]
    b = x**2 + y**2
    sol, _, _, _ = np.linalg.lstsq(A, b, rcond=None)
    cx, cy, c = sol
    r = np.sqrt(c + cx**2 + cy**2)
    return cx, cy, r

def visualize_and_save(input_folder, output_folder):
    os.makedirs(output_folder, exist_ok=True)
    files = [f for f in os.listdir(input_folder) if f.endswith('.json')]
    files.sort()

    for json_file in files:
        json_path = os.path.join(input_folder, json_file)
        with open(json_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        image_path = os.path.join(input_folder, data["imagePath"])
        if not os.path.exists(image_path):
            print(f"图像不存在：{image_path}")
            continue

        image = cv2.imread(image_path)

        for shape in data["shapes"]:
            label = shape["label"]
            points = np.array(shape["points"], dtype=np.float32)

            # 画关键点
            for (x, y) in points:
                cv2.circle(image, (int(x), int(y)), radius=3, color=(0, 255, 0), thickness=-1)

            # 拟合圆
            if points.shape[0] == 4:
                cx, cy, r = fit_circle(points)
                cv2.circle(image, (int(cx), int(cy)), int(r), (255, 0, 0), 2)  # 蓝色圆
                cv2.circle(image, (int(cx), int(cy)), 3, (0, 0, 255), -1)      # 圆心红点

            # 写标签
            x0, y0 = int(points[0][0]), int(points[0][1])
            cv2.putText(image, label, (x0, y0 - 5),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 1)

        resized_image = resize_to_fit(image)
        base_name = os.path.splitext(json_file)[0]
        save_path = os.path.join(output_folder, base_name + ".jpg")
        cv2.imwrite(save_path, resized_image)
        print(f"保存图片: {save_path}")

if __name__ == "__main__":
    visualize_and_save(input_folder, output_folder)
