Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick way to upsample numpy array by nearest neighbor tiling [duplicate]

Tags:

I have a 2D array of integers that is MxN, and I would like to expand the array to (BM)x(BN) where B is the length of a square tile side thus each element of the input array is repeated as a BxB block in the final array. Below is an example with a nested for loop. Is there a quicker/builtin way?

import numpy as np  a = np.arange(9).reshape([3,3])            # input array - 3x3 B=2.                                       # block size - 2   A = np.zeros([a.shape[0]*B,a.shape[1]*B])  # output array - 6x6  # Loop, filling A with tiled values of a at each index for i,l in enumerate(a):                   # lines in a     for j,aij in enumerate(l):             # a[i,j]         A[B*i:B*(i+1),B*j:B*(j+1)] = aij 

Result ...

a=      [[0 1 2]          [3 4 5]          [6 7 8]]  A =     [[ 0.  0.  1.  1.  2.  2.]          [ 0.  0.  1.  1.  2.  2.]          [ 3.  3.  4.  4.  5.  5.]          [ 3.  3.  4.  4.  5.  5.]          [ 6.  6.  7.  7.  8.  8.]          [ 6.  6.  7.  7.  8.  8.]] 
like image 454
mlh3789 Avatar asked Sep 29 '15 14:09

mlh3789


People also ask

How to resize an array using numpy?

With the help of Numpy numpy. resize(), we can resize the size of an array. Array can be of any shape but to resize it we just need the size i.e (2, 2), (2, 3) and many more. During resizing numpy append zeros if values at a particular place is missing.

How do I randomly select rows in Numpy?

Method 1: We will be using the function shuffle(). The shuffle() function shuffles the rows of an array randomly and then we will display a random row of the 2D array.

How does np resize work?

NumPy: resize() functionThe resize() function is used to create a new array with the specified shape. If the new array is larger than the original array, then the new array is filled with repeated copies of a. Array to be resized.


1 Answers

One option is

>>> a.repeat(2, axis=0).repeat(2, axis=1) array([[0, 0, 1, 1, 2, 2],        [0, 0, 1, 1, 2, 2],        [3, 3, 4, 4, 5, 5],        [3, 3, 4, 4, 5, 5],        [6, 6, 7, 7, 8, 8],        [6, 6, 7, 7, 8, 8]]) 

This is slightly wasteful due to the intermediate array but it's concise at least.

like image 146
YXD Avatar answered Oct 11 '22 11:10

YXD