70 lines
2.1 KiB
Python
70 lines
2.1 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]
|
||
|
||
# 创建四个掩码,初始化为全黑
|
||
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 / 2) + amplitude1 * np.sin(frequency1 * x)
|
||
|
||
# 第二条曲线(例如,余弦函数)
|
||
frequency2 = 4 * np.pi / width
|
||
amplitude2 = height / 6
|
||
y2 = (height / 2) + amplitude2 * np.cos(frequency2 * x)
|
||
|
||
# 确保y值在图像高度范围内
|
||
y1 = np.clip(y1, 0, height - 1)
|
||
y2 = np.clip(y2, 0, height - 1)
|
||
|
||
# 绘制第一个区域的掩码(曲线 y1 以上的区域)
|
||
for i in range(width):
|
||
cv2.line(mask1, (i, 0), (i, int(y1[i])), 255)
|
||
|
||
# 绘制第二个区域的掩码(曲线 y1 和 y2 之间的区域)
|
||
for i in range(width):
|
||
y_top = int(min(y1[i], y2[i]))
|
||
y_bottom = int(max(y1[i], y2[i]))
|
||
cv2.line(mask2, (i, y_top), (i, y_bottom), 255)
|
||
|
||
# 绘制第三个区域的掩码(曲线 y2 以下的区域)
|
||
for i in range(width):
|
||
cv2.line(mask3, (i, int(y2[i])), (i, height), 255)
|
||
|
||
# 绘制第四个区域的掩码(剩余区域)
|
||
mask4 = cv2.bitwise_not(cv2.bitwise_or(cv2.bitwise_or(mask1, mask2), mask3))
|
||
|
||
# 创建掩码列表
|
||
masks = [mask1, mask2, mask3, mask4]
|
||
|
||
# 确保输出目录存在
|
||
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("图片已成功切割成4张,并保存到 'output' 目录下。")
|