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 = np.arange(width)

# 第一条曲线（正弦函数）
frequency1 = 2 * np.pi / width
amplitude1 = height / 4
y1 = (height / 4) + amplitude1 * np.sin(frequency1 * x)

# 第二条曲线（余弦函数）
frequency2 = 4 * np.pi / width
amplitude2 = height / 4
y2 = (height / 2) + amplitude2 * np.cos(frequency2 * x)

# 第三条曲线（不同频率的正弦函数）
frequency3 = 6 * np.pi / width
amplitude3 = height / 4
y3 = (3 * height / 4) + amplitude3 * np.sin(frequency3 * x)

# 确保y值在图像高度范围内
y1 = np.clip(y1, 0, height - 1)
y2 = np.clip(y2, 0, height - 1)
y3 = np.clip(y3, 0, height - 1)

# 绘制第一个区域的掩码（从顶部到y1）
for i in range(width):
    y_top = 0
    y_bottom = int(y1[i])
    cv2.line(mask1, (i, y_top), (i, y_bottom), 255)

# 绘制第二个区域的掩码（从y1到y2）
for i in range(width):
    y_top = int(y1[i])
    y_bottom = int(y2[i])
    if y_bottom >= y_top:
        cv2.line(mask2, (i, y_top), (i, y_bottom), 255)
    else:
        cv2.line(mask2, (i, y_bottom), (i, y_top), 255)

# 绘制第三个区域的掩码（从y2到y3）
for i in range(width):
    y_top = int(y2[i])
    y_bottom = int(y3[i])
    if y_bottom >= y_top:
        cv2.line(mask3, (i, y_top), (i, y_bottom), 255)
    else:
        cv2.line(mask3, (i, y_bottom), (i, y_top), 255)

# 绘制第四个区域的掩码（从y3到底部）
for i in range(width):
    y_top = int(y3[i])
    y_bottom = height - 1
    cv2.line(mask4, (i, y_top), (i, y_bottom), 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' 目录下。")
