import cv2 import numpy as np import os # 读取输入图像 image = cv2.imread('input.jpg') # 检查图像是否读取成功 if image is None: print("无法读取 input.jpg,请确保文件存在且路径正确。") exit() # 获取图像的尺寸 height, width = image.shape[:2] # 创建四个掩码,初始化为全黑 mask1 = np.zeros((height, width), dtype=np.uint8) # 左上角 mask2 = np.zeros((height, width), dtype=np.uint8) # 右上角 mask3 = np.zeros((height, width), dtype=np.uint8) # 左下角 mask4 = np.zeros((height, width), dtype=np.uint8) # 右下角 # 定义横向曲线(沿着 x 轴变化) x = np.arange(width) num_bends = 4 # 4个弯曲 frequency_h = num_bends * 2 * np.pi / width amplitude_h = height / 20 # 调整幅度为图像高度的 1/20,幅度较小 y_h = (height / 2) + amplitude_h * np.sin(frequency_h * x) y_h = np.clip(y_h, 0, height - 1).astype(int) # 确保 y 值在图像范围内 # 定义纵向曲线(沿着 y 轴变化) y = np.arange(height) frequency_v = num_bends * 2 * np.pi / height amplitude_v = width / 20 # 调整幅度为图像宽度的 1/20,幅度较小 x_v = (width / 2) + amplitude_v * np.sin(frequency_v * y) x_v = np.clip(x_v, 0, width - 1).astype(int) # 确保 x 值在图像范围内 # 创建掩码 for i in range(height): for j in range(width): # 获取当前像素相对于曲线的位置 y_curve = y_h[j] x_curve = x_v[i] if i <= y_curve and j <= x_curve: mask1[i, j] = 255 # 左上角 elif i <= y_curve and j > x_curve: mask2[i, j] = 255 # 右上角 elif i > y_curve and j <= x_curve: mask3[i, j] = 255 # 左下角 else: mask4[i, j] = 255 # 右下角 # 确保输出目录存在 output_dir = 'output' if not os.path.exists(output_dir): os.makedirs(output_dir) # 应用掩码并保存图片 masks = [mask1, mask2, mask3, mask4] for idx, mask in enumerate(masks): img_part = cv2.bitwise_and(image, image, mask=mask) cv2.imwrite(os.path.join(output_dir, f'output{idx + 1}.png'), img_part) print("图片已成功切割成4张,并保存到 'output' 目录下。")