要求:将图片裁剪成九宫格,宫格图片位置打乱
思路:
- 判断该图片长宽是否能被3整除,不能需要对图片进行裁剪(我的是边角裁剪)
- 双重for循环,根据步长对图片数组进行切片达到裁剪效果
- random.shuffle()达到图片位置打乱的效果
- 使用np.concatenate()对图片数组按维拼接
代码:
第三方库
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import random
import math
判断函数
def judge(img, n=9):
x = int(math.sqrt(n))
w, h, _ = img.shape
if w % x:
w = (w // x) * x
if h % x:
h = (h // x) * x
return w, h
裁剪拼接函数
def crop_nine(new_image):
shape_w, shape_h, _ = new_image.shape
patch_w = shape_w // 3
patch_h = shape_h // 3
patch = []
for w in range(0, shape_w, patch_w):
for h in range(0, shape_h, patch_h):
patch.append(new_image[w:w+patch_w, h:h+patch_h, :])
random.shuffle(patch)
img_1 = np.concatenate((patch[0], patch[1], patch[2]), axis=0)
img_2 = np.concatenate((patch[3], patch[4], patch[5]), axis=0)
img_3 = np.concatenate((patch[6], patch[7], patch[8]), axis=0)
img = np.concatenate((img_1, img_2, img_3), axis=1)
return img
运行部分:
image_path = "dog.jpg"
img = np.array(Image.open(image_path))
w, h = judge(img)
new_image = img[:w, :h, :]
new_image = crop_nine(new_image)
plt.imshow(new_image)
效果:
|