import os
import cv2
import shutil

def resize_images(input_dir, output_dir, size=(512, 512)):
    """
    调整输入目录中的所有图像大小，并将图像和 JSON 一起保存到输出目录。

    :param input_dir: 输入图像目录路径
    :param output_dir: 输出图像目录路径
    :param size: 目标图像大小，默认为 (512, 512)
    """
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)

    # 遍历所有文件
    for filename in os.listdir(input_dir):
        input_path = os.path.join(input_dir, filename)
        output_path = os.path.join(output_dir, filename)

        # 如果是图像文件，执行缩放
        if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff')):
            try:
                img = cv2.imread(input_path)
                if img is not None:
                    resized_img = cv2.resize(img, size, interpolation=cv2.INTER_NEAREST)
                    cv2.imwrite(output_path, resized_img)
                    print(f"Resized and saved image: {output_path}")
                else:
                    print(f"Warning: Image is None - {filename}")
            except Exception as e:
                print(f"Error processing image {filename}: {e}")

        # 如果是 JSON 文件，直接复制
        elif filename.lower().endswith('.json'):
            try:
                shutil.copy2(input_path, output_path)
                print(f"Copied JSON file: {output_path}")
            except Exception as e:
                print(f"Error copying JSON {filename}: {e}")

# 使用示例
input_directory = r"G:\python_ws_g\data\a_strong_json_output"
parent_dir = os.path.dirname(input_directory)
output_directory = os.path.join(parent_dir, "a_strong_512")

resize_images(input_directory, output_directory)
