在图像大小调整插值问题中,可以使用 np.meshgrid
在对网格索引进行操作之前,在 row 和 col 索引上:
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, :]
现在,我将如何扭转这个过程?说给定
rr_1
, cc_1
( np.meshgrid
的产品)以未知方式处理(此处由 np.random.randint
说明),我如何获得 r_1
和 c_1
,即 np.meshgrid
的输入(最好使用 ij
索引)?# 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 = ?
更新:
发帖后我马上就想通了。答案是:
# 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]
最佳答案
numpy.meshgrid
从输入数组创建一个更高维的数组,以创建类似网格的数组。所以想象一下你想通过使用一些输入的一维向量来获得一个二维网格 r
和 c
. numpy.meshgrid
返回 rr
和 cc
作为 2D 阵列,它们分别在 2D 阵列上的任何地方保持 y 轴或 x 轴常数(这就是它是网格的原因)。
这是一个测试用例:
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]
请注意,我们为
rr
创建的网格和 cc
是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]]
由于您使用的是
indexing='ij'
在你的情况下,二维数组被转置。因此,对于 rr
保持不变的值和 cc
分别是 x 轴和 y 轴(与您不使用 indexing='ij'
的情况相反)。
关于python - 如何撤消或反转 np.meshgrid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53385605/