Home > OS >  Scale an array with zero values in numpy python
Scale an array with zero values in numpy python

Time:10-06

I have an array like this:

[[1 2 3 4]
 [9 8 7 6]]

and want to upscale like this:

[[1 0 0 2 0 0 3 0 0 4 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0]
 [9 0 0 8 0 0 7 0 0 6 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0]]

Try with numpt.pad, numpy.insert and numpy.kron but cant access the answer.

CodePudding user response:

You can just use assignment here. If n might be different for width and height, just index using result[::h, ::w].

n = 3
result = np.zeros(np.array(a.shape) * n, dtype=int)
result[::n, ::n] = a

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

If you really want to use kron, a similar principal can be applied, by making a mask with only the desired element set to 1.

kernel = np.zeros((3, 3), dtype=int)
kernel[0, 0] = 1
np.kron(a, kernel)
  • Related