Downsampling 3D array with numpy

Question:

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]]])
Asked By: Average Leaner

||

Answers:

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]
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.