Initial commit
This commit is contained in:
64
split05.py
Normal file
64
split05.py
Normal file
@@ -0,0 +1,64 @@
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
def generate_curve_points(width, height, num_points=10):
|
||||
"""生成曲线的控制点,并绘制平滑曲线"""
|
||||
# 随机生成控制点
|
||||
points = np.array([(x, np.random.randint(0, height)) for x in np.linspace(0, width, num_points)])
|
||||
# 使用样条曲线生成平滑曲线
|
||||
curve = cv2.approxPolyDP(points, 1, closed=False)
|
||||
return curve.reshape(-1, 2)
|
||||
|
||||
def split_image_with_curve(image, curve, grid_size=10):
|
||||
"""使用曲线将图像分割为小块"""
|
||||
h, w = image.shape[:2]
|
||||
grid_h, grid_w = h // grid_size, w // grid_size
|
||||
pieces = []
|
||||
|
||||
# 遍历每个网格块
|
||||
for i in range(grid_size):
|
||||
for j in range(grid_size):
|
||||
# 计算网格块的范围
|
||||
x_start, y_start = j * grid_w, i * grid_h
|
||||
x_end, y_end = x_start + grid_w, y_start + grid_h
|
||||
|
||||
# 创建一个空白掩膜并绘制曲线
|
||||
mask = np.zeros((grid_h, grid_w), dtype=np.uint8)
|
||||
curve_segment = curve[np.logical_and(curve[:, 0] >= x_start, curve[:, 0] <= x_end)]
|
||||
for k in range(len(curve_segment) - 1):
|
||||
cv2.line(mask, tuple(curve_segment[k]), tuple(curve_segment[k + 1]), 255, 2)
|
||||
|
||||
# 将网格块切成上下两部分
|
||||
part1 = cv2.bitwise_and(image[y_start:y_end, x_start:x_end], image[y_start:y_end, x_start:x_end], mask=mask)
|
||||
part2 = cv2.bitwise_and(image[y_start:y_end, x_start:x_end], image[y_start:y_end, x_start:x_end], mask=cv2.bitwise_not(mask))
|
||||
|
||||
pieces.append((part1, part2))
|
||||
|
||||
return pieces
|
||||
|
||||
# 主程序
|
||||
if __name__ == "__main__":
|
||||
# 加载正方形图片
|
||||
image_path = "input.jpg" # 替换为你的图片路径
|
||||
image = cv2.imread(image_path)
|
||||
|
||||
if image is None:
|
||||
print("无法加载图片,请检查路径!")
|
||||
exit()
|
||||
|
||||
# 确保图片是正方形
|
||||
h, w = image.shape[:2]
|
||||
if h != w:
|
||||
print("图片不是正方形,请提供正方形图片!")
|
||||
exit()
|
||||
|
||||
# 生成曲线
|
||||
curve = generate_curve_points(w, h)
|
||||
|
||||
# 切割图片
|
||||
pieces = split_image_with_curve(image, curve)
|
||||
|
||||
# 保存分割块
|
||||
for idx, (part1, part2) in enumerate(pieces):
|
||||
cv2.imwrite(f"part1_{idx}.png", part1)
|
||||
cv2.imwrite(f"part2_{idx}.png", part2)
|
||||
Reference in New Issue
Block a user