如何使用 Python 将图像切片并编译成 window 效果

How to slice and complie an image into a window effect using Python

我想在 python 中分割图像 并将其重新粘贴为 window.

图块尺寸为 8 x 9 像素,每行需要跳过 1 个像素

然后我需要将这些图块再次合并在一起,并在每个图块周围填充 1 个像素以产生 windowed 效果。

图像是黑白的,但在示例中我使用了颜色来表明 windowed 效果需要有白色背景

input example

Desired Output

更新:将图块尺寸更改为更大以供说明,您可以根据需要进行调整
使用这个:

import cv2

image = cv2.imread('test.jpg')

tiles_height = 50
tiles_width = 30
# white padding
padding_x = 10
padding_y = 20

num_y = int(image.shape[0]/tiles_height)
num_x = int(image.shape[1]/tiles_width)
new_img = np.full((image.shape[0] + num_y*padding_y, image.shape[1] + num_x*padding_x,3),255)



for incre_i,i in enumerate(range(0,image.shape[0],tiles_height)):
  for incre_j,j in enumerate(range(0, image.shape[1], tiles_width)):
    new_img[i+incre_i*padding_y:i+tiles_height+incre_i*padding_y
            ,j+incre_j*padding_x:j+tiles_width+incre_j*padding_x,:] = image[i:i+tiles_height,j:j+tiles_width,:]
cv2.imwrite('res.jpg',new_img)
print(image.shape, new_img.shape)

更新 1: 因为您想稍后删除图块,所以我添加了可以帮助您的代码。现在您所要做的就是更改 tiles configwhite paddingtile index to be removed:

中的变量
import cv2

image = cv2.imread('test.jpg')

# tiles config
tiles_height = 50
tiles_width = 30
# white padding
padding_x = 10
padding_y = 20

# tile index to be removed
remove_indices = [(0,0),(3,6)]


num_y = int(image.shape[0]/tiles_height)
num_x = int(image.shape[1]/tiles_width)
new_img = np.full((image.shape[0] + num_y*padding_y, image.shape[1] + num_x*padding_x,3),255)

for incre_i,i in enumerate(range(0,image.shape[0],tiles_height)):
  for incre_j,j in enumerate(range(0, image.shape[1], tiles_width)):
    if (incre_i,incre_j) in remove_indices:
      new_img[i+incre_i*padding_y:i+tiles_height+incre_i*padding_y
            ,j+incre_j*padding_x:j+tiles_width+incre_j*padding_x,:] = 255
    else:
      new_img[i+incre_i*padding_y:i+tiles_height+incre_i*padding_y
              ,j+incre_j*padding_x:j+tiles_width+incre_j*padding_x,:] = image[i:i+tiles_height,j:j+tiles_width,:]
cv2.imwrite('remove_tiles.jpg',new_img)
print(image.shape, new_img.shape)

test.jpg res.jpg remove_tiles.jpg

print(image.shape, new_img.shape) 给出 (952, 1429, 3) (1332, 1899, 3)

您可以尝试使用 scikit-image 包中的 skimage.utils.view_as_windows

from skimage.util import view_as_windows
import matplotlib.pyplot as plt
import numpy as np

img = np.random.rand(90, 90, 1)  # gray-scale image, you can change the channels accordingly
img[8::9,] = 0
tiles = view_as_windows(img, (9, 9, 1), (9, 9, 1)).squeeze(2)  # squeeze out unneded dim
tiles = tiles[:, :, :-1, :, :]  # Remove last row of each tile

# plot the original image
plt.axis("off")
plt.imshow(img.squeeze(2))
plt.show()

# plot the tiles
fig, axes = plt.subplots(10, 10)
for i in range(10):
  for j in range(10):
    axes[i, j].axis("off")
    axes[i, j].imshow(tiles[i, j, ...].squeeze(-1))
plt.show()

结果如下:

原创

切片

PyTorch 中的 torch.Tensor.unfold 运算符也是一个选项。