87 lines
2.6 KiB
Python
87 lines
2.6 KiB
Python
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]
|
||
|
||
# 创建九个掩码,初始化为全黑
|
||
masks = [np.zeros((height, width), dtype=np.uint8) for _ in range(9)]
|
||
|
||
# 定义曲线参数
|
||
num_bends = 12 # 增加弯曲数
|
||
amplitude_h = height / 20 # 横向曲线的幅度
|
||
amplitude_v = width / 20 # 纵向曲线的幅度
|
||
|
||
# 定义两条横向曲线(沿着 x 轴变化)
|
||
x = np.arange(width)
|
||
frequency_h = num_bends * np.pi / width
|
||
|
||
y_h1 = (height / 3) + amplitude_h * np.sin(frequency_h * x)
|
||
y_h2 = (2 * height / 3) + amplitude_h * np.sin(frequency_h * x)
|
||
|
||
y_h1 = np.clip(y_h1, 0, height - 1).astype(int)
|
||
y_h2 = np.clip(y_h2, 0, height - 1).astype(int)
|
||
|
||
# 定义两条纵向曲线(沿着 y 轴变化)
|
||
y = np.arange(height)
|
||
frequency_v = num_bends * np.pi / height
|
||
|
||
x_v1 = (width / 3) + amplitude_v * np.sin(frequency_v * y)
|
||
x_v2 = (2 * width / 3) + amplitude_v * np.sin(frequency_v * y)
|
||
|
||
x_v1 = np.clip(x_v1, 0, width - 1).astype(int)
|
||
x_v2 = np.clip(x_v2, 0, width - 1).astype(int)
|
||
|
||
# 创建掩码
|
||
for i in range(height):
|
||
for j in range(width):
|
||
# 获取当前像素相对于曲线的位置
|
||
y_curve1 = y_h1[j]
|
||
y_curve2 = y_h2[j]
|
||
x_curve1 = x_v1[i]
|
||
x_curve2 = x_v2[i]
|
||
|
||
# 判断所在区域
|
||
if i <= y_curve1:
|
||
if j <= x_curve1:
|
||
masks[0][i, j] = 255 # 左上角
|
||
elif j <= x_curve2:
|
||
masks[1][i, j] = 255 # 上中
|
||
else:
|
||
masks[2][i, j] = 255 # 右上角
|
||
elif i <= y_curve2:
|
||
if j <= x_curve1:
|
||
masks[3][i, j] = 255 # 中左
|
||
elif j <= x_curve2:
|
||
masks[4][i, j] = 255 # 中间
|
||
else:
|
||
masks[5][i, j] = 255 # 中右
|
||
else:
|
||
if j <= x_curve1:
|
||
masks[6][i, j] = 255 # 左下角
|
||
elif j <= x_curve2:
|
||
masks[7][i, j] = 255 # 下中
|
||
else:
|
||
masks[8][i, j] = 255 # 右下角
|
||
|
||
# 确保输出目录存在
|
||
output_dir = 'output'
|
||
if not os.path.exists(output_dir):
|
||
os.makedirs(output_dir)
|
||
|
||
# 应用掩码并保存图片
|
||
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("图片已成功切割成9张,并保存到 'output' 目录下。")
|