0

我想在 python 中切片图像并将其作为窗口再次粘贴在一起。

瓷砖尺寸为 8 像素 x 9 像素,每行需要跳过 1 像素

然后我需要将这些图块重新合并在一起,并在每个图块周围使用 1 个像素填充以产生窗口效果。

图像是黑白的,但对于示例,我使用颜色来显示窗口效果需要具有白色背景

输入示例

期望的输出

4

2 回答 2

0

更新:将瓷砖尺寸更改为更大以进行说明,您可以根据需要进行调整
使用此:

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 config, white padding,中的变量tile 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)

于 2021-11-26T13:41:46.180 回答
0

skimage.utils.view_as_windows您可以从scikit-image包中尝试:

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()

结果如下:

原来的

原来的

切片

在此处输入图像描述

PyTorchtorch.Tensor.unfold运算符也可以是一个选项。

于 2021-11-26T17:14:00.340 回答