import os import json import cv2 import numpy as np input_folder = r"G:\python_ws_g\data\arcout" # 你的 JSON + 图片输入文件夹 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_AREA) return resized_image 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 = shape["points"] pts = np.array(points, dtype=np.int32).reshape((-1, 1, 2)) color = (0, 255, 0) cv2.polylines(image, [pts], isClosed=True, color=color, thickness=2) x0, y0 = pts[0][0] cv2.putText(image, label, (x0, y0 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 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)