Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to undo or reverse np.meshgrid?

In an image resizing interpolation problem, one could use np.meshgrid on row and col indices before operating on the meshed indices:

nrows = 600
ncols = 800
image_in = np.random.randint(0, 256, size=(nrows, ncols, 3))
scale_factor = 1.5

r = np.arange(nrows, dtype=float) * scale_factor
c = np.arange(ncols, dtype=float) * scale_factor

rr, cc = np.meshgrid(r, c, indexing='ij')

# Nearest Neighbor Interpolation
# np.floor if scale_factor >= 1. np.ceil otherwise
rr = np.floor(rr).astype(int).clip(0, nrows-1)
cc = np.floor(cc).astype(int).clip(0, ncols-1)

image_out = image_in[rr, cc, :]

Now, how would I reverse this process? Say given rr_1, cc_1 (product of np.meshgrid) that's processed in an unknown manner (here illustrated by np.random.randint), how do I get the r_1 and c_1, that is, the inputs to np.meshgrid (preferably with ij indexing)?

# Suppose rr_1, cc_1 = np.meshgrid(r_1, c_1, indexing='ij')
rr_1 = np.random.randint(0, nrows, size=(nrows, ncols, 3))
cc_1 = np.random.randint(0, ncols, size=(nrows, ncols, 3))

r_1 = ?
c_1 = ?

UPDATE:

I figured it out immediately after posting. The answer is:

# Suppose rr_1, cc_1 = np.meshgrid(r_1, c_1, indexing='ij')
rr_1 = np.random.randint(0, nrows, size=(nrows, ncols, 3))
cc_1 = np.random.randint(0, ncols, size=(nrows, ncols, 3))

r_1 = rr_1[:, 0]
c_1 = cc_1[0]
like image 688
Zhanwen Chen Avatar asked Nov 20 '18 03:11

Zhanwen Chen


1 Answers

The numpy.meshgrid creates a higher dimensional array from input arrays in order to create grid-like arrays. So imagine you want to get a 2D grid by using some input 1D vectors r and c. numpy.meshgrid returns rr and cc as 2D arrays which respectively hold the y axis or x axis constant everywhere on the 2D array (this is why it is a grid).

Here is a test case:

import numpy as np

r = np.arange(5)      # [0 1 2 3 4]
c = np.arange(5,10,1) # [5 6 7 8 9]

rr, cc = np.meshgrid(r,c,indexing='ij')

r_original = rr[:,0]
c_original = cc[0,:]

print(r_original)     # [0 1 2 3 4]
print(c_original)     # [5 6 7 8 9]

Note that the grids we have created for rr and cc are

rr = [[0 0 0 0 0]
      [1 1 1 1 1]
      [2 2 2 2 2]
      [3 3 3 3 3]
      [4 4 4 4 4]]

cc = [[5 6 7 8 9]
      [5 6 7 8 9]
      [5 6 7 8 9]
      [5 6 7 8 9]
      [5 6 7 8 9]]

Since you are using indexing='ij' in your case and the 2D arrays are transposed. Hence, the values that hold constant for rr and cc respectively are the x axis and y axis (contrary to the case where you do not use indexing='ij').

like image 124
b-fg Avatar answered Oct 17 '22 20:10

b-fg