import os
import cv2
import numpy as np

# 输入和输出文件夹
input_folder = 'output10'
output_folder = 'output11'

# 确保输出文件夹存在
os.makedirs(output_folder, exist_ok=True)

# 遍历输入文件夹中的所有图片
for filename in os.listdir(input_folder):
    filepath = os.path.join(input_folder, filename)

    # 检查是否是图片文件
    if not filename.lower().endswith(('.png', '.jpg', '.jpeg')):
        continue

    # 读取图片
    image = cv2.imread(filepath, cv2.IMREAD_UNCHANGED)

    if image is None:
        print(f"无法读取文件: {filepath}")
        continue

    # 检查是否有 alpha 通道
    if image.shape[2] == 4:
        alpha_channel = image[:, :, 3]
        _, binary_mask = cv2.threshold(alpha_channel, 1, 255, cv2.THRESH_BINARY)
    else:
        # 如果没有 alpha 通道，直接将非黑色区域作为非透明区域
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        _, binary_mask = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY)

    # 找到非透明区域的轮廓
    contours, _ = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    if contours:
        # 获取最大轮廓的最小旋转矩形
        largest_contour = max(contours, key=cv2.contourArea)
        rect = cv2.minAreaRect(largest_contour)
        box = cv2.boxPoints(rect)
        box = np.intp(box)  # 修正数据类型

        # 在原图上绘制矩形
        result_image = image.copy()
        if image.shape[2] == 4:  # 如果有 alpha 通道
            result_image = cv2.cvtColor(result_image, cv2.COLOR_BGRA2BGR)
        cv2.drawContours(result_image, [box], 0, (0, 255, 0), 2)

        # 保存结果图片
        output_path = os.path.join(output_folder, filename)
        cv2.imwrite(output_path, result_image)

print("处理完成，结果已保存到 output11 文件夹中。")
