Home > OS >  Downsampling 3D array with numpy
Downsampling 3D array with numpy

Time:10-06

Given array:

A = array([[[1, 2, 3, 1],
            [4, 5, 6, 2],
            [7, 8, 9, 3]]])

I obtain the following array in the forward pass with a downsampling factor of k-1:

k = 3
B = A[...,::k]

#output  
array([[[1, 1],
        [4, 2],
        [7, 3]]])

In the backward pass I want to be able to come back to my original shape, with an output of:

array([[[1, 0, 0, 1],
        [4, 0, 0, 2],
        [7, 0, 0, 3]]])

CodePudding user response:

You can use numpy.zeros to initialize the output and indexing:

shape = list(B.shape)
shape[-1] = k*(shape[-1]-1) 1
# [1, 3, 4]

A2 = np.zeros(shape, dtype=B.dtype)
A2[..., ::k] = B

print(A2)

output:

array([[[1, 0, 0, 1],
        [4, 0, 0, 2],
        [7, 0, 0, 3]]])

using A:

A2 = np.zeros_like(A)
A2[..., ::k] = B
# or directly
# A2[..., ::k] = A[..., ::k]
  • Related