Expanding / scaling in numpy array

I have the following array:

import numpy as np
a = np.array([[2, 3, 5],
              [4, 6, 7],
              [1, 5, 7]])

      

I want to expand it to this array:

b = [[2 2 2 3 3 3 5 5 5]
     [2 2 2 3 3 3 5 5 5]
     [2 2 2 3 3 3 5 5 5]
     [4 4 4 6 6 6 7 7 7]
     [4 4 4 6 6 6 7 7 7]
     [4 4 4 6 6 6 7 7 7]
     [1 1 1 5 5 5 7 7 7]
     [1 1 1 5 5 5 7 7 7]
     [1 1 1 5 5 5 7 7 7]]

      

So, I am using the following command:

import scipy.ndimage
b = scipy.ndimage.interpolation.zoom(a, 3, order=0)

      

based on this question and answer here Resampling the numpy array representing the image .

However, I get the following:

b = [[2 2 3 3 3 3 5 5 5]
     [2 2 3 3 3 3 5 5 5]
     [4 4 6 6 6 6 7 7 7]
     [4 4 6 6 6 6 7 7 7]
     [4 4 6 6 6 6 7 7 7]
     [4 4 6 6 6 6 7 7 7]
     [1 1 5 5 5 5 7 7 7]
     [1 1 5 5 5 5 7 7 7]
     [1 1 5 5 5 5 7 7 7]]

      

I want the expansion to be exactly 3, or whatever the scaling factor, but it is currently different for every element in the array.

Is there a direct way to do this? Or will I do it manually with some coding?

+3


source to share


2 answers


Maybe a little late, but for the sake of completeness: Numpy Kron does the job just fine



>>> import numpy as np
>>> a = np.array([[2,3,5], [4,6,7], [1,5,7]])
>>> np.kron(a, np.ones((3,3)))
array([[ 2.,  2.,  2.,  3.,  3.,  3.,  5.,  5.,  5.],
       [ 2.,  2.,  2.,  3.,  3.,  3.,  5.,  5.,  5.],
       [ 2.,  2.,  2.,  3.,  3.,  3.,  5.,  5.,  5.],
       [ 4.,  4.,  4.,  6.,  6.,  6.,  7.,  7.,  7.],
       [ 4.,  4.,  4.,  6.,  6.,  6.,  7.,  7.,  7.],
       [ 4.,  4.,  4.,  6.,  6.,  6.,  7.,  7.,  7.],
       [ 1.,  1.,  1.,  5.,  5.,  5.,  7.,  7.,  7.],
       [ 1.,  1.,  1.,  5.,  5.,  5.,  7.,  7.,  7.],
       [ 1.,  1.,  1.,  5.,  5.,  5.,  7.,  7.,  7.]])

      

+5


source


I don't know if there is a function that does exactly what you want in NumPy or SciPy, but it's easy to create one yourself:

from __future__ import division
import numpy as np

def zoom(a, factor):
    a = np.asarray(a)
    slices = [slice(0, old, 1/factor) for old in a.shape]
    idxs = (np.mgrid[slices]).astype('i')
    return a[tuple(idxs)]

      

It gives the expected output:



>>> a = [[2,3,5], [4,6,7], [1,5,7]]

>>> zoom(a,3)
array([[2, 2, 2, 3, 3, 3, 5, 5, 5],
       [2, 2, 2, 3, 3, 3, 5, 5, 5],
       [2, 2, 2, 3, 3, 3, 5, 5, 5],
       [4, 4, 4, 6, 6, 6, 7, 7, 7],
       [4, 4, 4, 6, 6, 6, 7, 7, 7],
       [4, 4, 4, 6, 6, 6, 7, 7, 7],
       [1, 1, 1, 5, 5, 5, 7, 7, 7],
       [1, 1, 1, 5, 5, 5, 7, 7, 7],
       [1, 1, 1, 5, 5, 5, 7, 7, 7]])

      

I haven't tested it for all factors and shapes, maybe this approach could cause problems due to floating point precision (step argument in slices).

+1


source







All Articles