import os
import cv2
import numpy as np


def process_png(file_path, output_folder):
    image = cv2.imread(file_path, cv2.IMREAD_UNCHANGED)
    if image is None:
        print(f"无法读取图像：{file_path}")
        return

    if image.shape[2] < 4:
        print(f"图像没有 alpha 通道：{file_path}")
        return

    alpha = image[:, :, 3]
    _, thresh = cv2.threshold(alpha, 0, 255, cv2.THRESH_BINARY)
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    if not contours:
        print(f"图像中没有非透明部分：{file_path}")
        return

    cnt = max(contours, key=cv2.contourArea)
    rect = cv2.minAreaRect(cnt)
    box = cv2.boxPoints(rect)
    box = np.int32(box)

    # 提取最小矩形内的图像并旋转
    width = int(rect[1][0])
    height = int(rect[1][1])

    if width == 0 or height == 0:
        print(f"最小矩形的宽度或高度为零：{file_path}")
        return

    src_pts = box.astype("float32")
    # 定义目标点为水平矩形
    dst_pts = np.array([
        [0, height - 1],
        [0, 0],
        [width - 1, 0],
        [width - 1, height - 1]
    ], dtype="float32")

    # 计算透视变换矩阵
    M = cv2.getPerspectiveTransform(src_pts, dst_pts)
    warped = cv2.warpPerspective(image, M, (width, height))

    base, ext = os.path.splitext(os.path.basename(file_path))
    extracted_filename = f"{base}_extracted{ext}"
    extracted_path = os.path.join(output_folder, extracted_filename)

    # 保存带 alpha 通道的图像
    if warped.shape[2] == 4:
        cv2.imwrite(extracted_path, warped)
    else:
        # 如果没有 alpha 通道，转换为 RGB
        cv2.imwrite(extracted_path, cv2.cvtColor(warped, cv2.COLOR_BGR2RGB))

    print(f"提取并旋转后的图像已保存为：{extracted_path}")


def main():
    input_folder = 'output'
    output_folder = 'output2'

    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    png_files = [f for f in os.listdir(input_folder) if f.lower().endswith('.png')]

    if not png_files:
        print("在指定的文件夹中未找到 PNG 文件。")
        return

    for filename in png_files:
        file_path = os.path.join(input_folder, filename)
        print(f"正在处理文件：{file_path}")
        process_png(file_path, output_folder)


if __name__ == "__main__":
    main()
