Dado um array 4D de tamanho (N,W,H,3), onde N é o número de patches, W,H são a largura e altura de um patch de imagem e 3 é o número de canais de cor. Suponha que esses patches foram gerados pegando uma imagem original I e dividindo-a em pequenos quadrados. A ordem pela qual essa divisão acontece é linha por linha. Então, se dividirmos nossa imagem em patches 3x3 (9 no total), cada um com 10x10 pixels, então o array 4D será (9,10,10,3) e a ordem dos elementos nele será [patch11,patch12,patch13,patch21,patch22,patch23,patch31,patch32,patch33].
Agora, minha pergunta é sobre a maneira mais eficiente de combinar esses patches de volta para produzir a imagem original apenas em Python, usando apenas funções Python e numpy (sem PIL ou OpenCV).
Muito obrigado.
Posso escrever um loop duplo que faça o trabalho conforme abaixo, mas estou pensando se existe um algoritmo melhor que possa fornecer um desempenho mais rápido:
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)
Aqui vai uma maneira rápida e simples de fazer isso:
Explicação: Primeiro,
reshape
reestrutura sua matriz como uma matriz "2D" de patches,swapaxes
cria sua matriz(num_rows, W, num_cols, H, C)
e, finalmente, o segundo e últimoreshape
concatena efetivamente os patches em linhas e colunas.Comparação de tempo: