python - 如何撤消或反转 np.meshgrid?

标签 python numpy image-processing

在图像大小调整插值问题中,可以使用 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_1c_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从输入数组创建一个更高维的数组,以创建类似网格的数组。所以想象一下你想通过使用一些输入的一维向量来获得一个二维网格 rc . numpy.meshgrid返回 rrcc作为 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/

相关文章:

python pandas np.where 来自另一列的值

python - 为什么 itertools.groupby 可以将 NaN 分组在列表中而不是在 numpy 数组中

python - 我需要使用 numpy 的矢量化来优化我的双 for 循环

opencv - OpenCV中霍夫圆和minEnclosed圆检测圆的区别?

algorithm - 聚类一组矩形

python - 进程线程无法感知全局变量的变化

python - boto 库是线程安全的吗?

python - numpy中如何计算重复数组?

python - np.linspace 和 np.arange 有什么区别?

opencv - 如何在OpenCV中沿其轮廓裁剪给定的不规则形状的对象