import os import cv2 import numpy as np def process_merged_image(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("图像中没有非透明部分。") return for idx, cnt in enumerate(contours, start=1): 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"第 {idx} 个最小矩形的宽度或高度为零,跳过。") continue 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_{idx}{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_image = os.path.join('output3', 'merged_image.png') output_folder = 'output4' if not os.path.exists(output_folder): os.makedirs(output_folder) if not os.path.isfile(input_image): print(f"输入图像不存在:{input_image}") return print(f"正在处理图像:{input_image}") process_merged_image(input_image, output_folder) if __name__ == "__main__": main()