【问题标题】:Translating float index interpolation from MATLAB to Python将浮点索引插值从 MATLAB 转换为 Python
【发布时间】:2020-12-26 15:30:31
【问题描述】:

例如,我有一个索引数组

ax = [0, 0.2, 2] #start from index 0: python

和矩阵I

I= 
10    20    30    40    50
10    20    30    40    50
10    20    30    40    50
10    20    30    40    50
10    20    30    40    50

在 MATLAB 中,通过运行此代码

[gx, gy] = meshgrid([1,1.2,3], [1,1.2,3]);
I = [10:10:50];
I = vertcat(I,I,I,I,I)
SI = interp2(I,gx,gy,'bilinear');

生成的SI

SI =
10    12    30
10    12    30
10    12    30

我尝试在 Python 中使用 NumPy 进行相同的插值。我首先按行插入,然后按列插入

import numpy as np
ax = np.array([0.0, 0.2, 2.0])
ay = np.array([0.0, 0.2, 2.0])
I = np.array([[10,20,30,40,50]])
I = np.concatenate((I,I,I,I,I), axis=0)
r_idx = np.arange(1, I.shape[0]+1)
c_idx = np.arange(1, I.shape[1]+1)
  
I_row = np.transpose(np.array([np.interp(ax, r_idx, I[:,x]) for x in range(0,I.shape[0])]))
I_col = np.array([np.interp(ay, c_idx, I_row[y,:]) for y in range(0, I_row.shape[0])])

SI = I_col

但是,生成的SI

SI =
10    10    20
10    10    20
10    10    20

为什么我使用 Python 的结果与使用 MATLAB 的结果不同?

【问题讨论】:

    标签: python matlab numpy interpolation


    【解决方案1】:

    您从 MATLAB 传递到 Python 似乎过度纠正了自己,如您的第一个代码摘录所示。

    ax = [0, 0.2, 2] #start from index 0: python
    

    在 numpy 逻辑中,这个序列不代表索引而是坐标 用于插值的函数。 由于您已经在此处处理了增加坐标以与 matlab 兼容:

    r_idx = np.arange(1, I.shape[0]+1)
    c_idx = np.arange(1, I.shape[1]+1)
    

    您可以重复使用在 Matlab 中使用的相同插值坐标:

    ax = [1,1.2,3]
    

    完整代码:

    import numpy as np
    ax = np.array([1.0, 1.2, 3.0])
    ay = np.array([1.0, 1.2, 3.0])
    I = np.array([[10,20,30,40,50]])
    I = np.concatenate((I,I,I,I,I), axis=0)
    r_idx = np.arange(1, I.shape[0]+1)
    c_idx = np.arange(1, I.shape[1]+1)
    
    I_row = np.transpose(np.array([np.interp(ax, r_idx, I[:,x]) for x in range(0,I.shape[
    0])]))
    I_col = np.array([np.interp(ay, c_idx, I_row[y,:]) for y in range(0, I_row.shape[0])]
    )
    
    SI = I_col
    

    结果:

    array([[10., 12., 30.],
           [10., 12., 30.],
           [10., 12., 30.]])
    

    错误说明

    由于ax 表示坐标,所以前两个值0.00.2r_idx 的第一个坐标之前。 根据documentation,插值将默认为I[:,x][0]。

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 2020-03-21
      • 2013-07-01
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      • 2022-07-23
      • 1970-01-01
      • 2017-10-14
      相关资源
      最近更新 更多