如何在Python中将图像分割成块,处理它们,然后将它们重新合并在一起?

2024-10-01 02:39:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把我的图像分成4x4块,然后放大每个块,最后把它们合并在一起

我已经参考了Stackoverflow的各种方法,但它们没有提到如何将块重新合并在一起

enter image description here


Tags: 方法图像stackoverflow将块
1条回答
网友
1楼 · 发布于 2024-10-01 02:39:19

下面是我对this post的答案的复制粘贴,并添加了如何重新组合图像: 我会像我在下面代码中所做的那样做smth。在我的示例中,我使用了skimage.data中的部分图像来说明我的方法,并使其形状和大小不同,以便看起来更漂亮。但您可以通过调整这些参数对dta执行相同的操作

from skimage import data
from matplotlib import pyplot as plt
import numpy as np

astronaut = data.astronaut()
coffee    = data.coffee()

arr = np.stack([coffee[:400, :400, :], astronaut[:400, :400, :]])
plt.imshow(arr[0])
plt.title('arr[0]')
plt.figure()
plt.imshow(arr[1])
plt.title('arr[1]')

arr_blocks = arr.reshape(arr.shape[0], 4, 100, 4, 100, 3, ).swapaxes(2, 3)
arr_blocks = arr_blocks.reshape(-1, 100, 100, 3)


for i, block in enumerate(arr_blocks):
    plt.figure(10+i//16, figsize = (10, 10))
    plt.subplot(4, 4, i%16+1)
    plt.imshow(block)
    plt.title(f'block {i}')

# batch_size = 9
# some_outputs_list = []
# for i in range(arr_blocks.shape[0]//batch_size + ((arr_blocks.shape[0]%batch_size) > 0)):
#     some_outputs_list.append(some_function(arr_blocks[i*batch_size:(i+1)*batch_size]))

输出:

enter image description here

enter image description here

enter image description here

为了重新组装图像,我会这样做:

arr_blocks = arr_blocks.reshape(-1, 4, 4, 100, 100, 3).swapaxes(2, 3)
arr_blocks = arr_blocks.reshape(-1, 400, 400, 3)

for i, block in enumerate(arr_blocks):
    plt.figure()
    plt.imshow(block)
    plt.title('reconstruction {i}')

输出:

enter image description here

相关问题 更多 >