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]
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'
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With