给定一个大小为 (N,W,H,3) 的 4D 数组,其中 N 是补丁数,W、H 是图像补丁的宽度和高度,3 是颜色通道数。假设这些补丁是通过获取原始图像 I 并将其分成小方块生成的。这种划分的顺序是逐行进行的。因此,如果我们将图像分成 3x3 个补丁(总共 9 个),每个补丁为 10x10 像素,则 4D 数组将为 (9,10,10,3),其中元素的顺序将为 [patch11,patch12,patch13,patch21,patch22,patch23,patch31,patch32,patch33]。
现在我的问题是关于最有效的方法将这些补丁组合回来以仅使用简单的 python 函数和 numpy(没有 PIL 或 OpenCV)在 python 中生成原始图像。
太感谢了。
我可以编写一个双 for 循环来完成下面的工作,但我想知道是否有更好的算法可以提供更快的性能:
import numpy as np
def reconstruct_image(patches, num_rows, num_cols):
# num_rows and num_cols are the number of patches in the rows and columns respectively
patch_height, patch_width, channels = patches.shape[1], patches.shape[2], patches.shape[3]
# Initialize the empty array for the full image
full_image = np.zeros((num_rows * patch_height, num_cols * patch_width, channels), dtype=patches.dtype)
# Iterate over the rows and columns of patches
for i in range(num_rows):
for j in range(num_cols):
# Get the index of the current patch in the 4D array
patch_index = i * num_cols + j
# Place the patch in the appropriate position in the full image
full_image[i*patch_height:(i+1)*patch_height, j*patch_width:(j+1)*patch_width, :] = patches[patch_index]
return full_image
N = 9 # Number of patches
W, H, C = 10, 10, 3 # Patch dimensions (WxHxC)
num_rows, num_cols = 3, 3 # Number of patches in rows and columns (3x3 patches)
patches = np.random.rand(N, W, H, C) # Example patch data
reconstructed_image = reconstruct_image(patches, num_rows, num_cols)
这是一个快速的纯 numpy 单行方法来实现它:
解释:首先
reshape
将您的数组重构为一个“2D”补丁数组,swapaxes
使您的数组成为(num_rows, W, num_cols, H, C)
,最后第二个也是最后一个reshape
有效地将补丁按行和列连接在一起。时序比较: