移位插值不会产生预期的行为

bpr*_*auf 7 python interpolation scipy ndimage

当使用scipy.ndimage.interpolation.shift使用周期性边界处理(mode = 'wrap')沿一个轴移动numpy数据数组时,我得到一个意外的行为.例程尝试强制第一个pixel(index 0)与最后一个(index N-1)相同而不是"last plus one(index N)".

最小的例子:

# module import
import numpy as np
from scipy.ndimage.interpolation import shift
import matplotlib.pyplot as plt

# print scipy.__version__
# 0.18.1

a = range(10)

plt.figure(figsize=(16,12))

for i, shift_pix in enumerate(range(10)):
    # shift the data via spline interpolation
    b = shift(a, shift=shift_pix, mode='wrap')

    # plotting the data
    plt.subplot(5,2,i+1)
    plt.plot(a, marker='o', label='data')
    plt.plot(np.roll(a, shift_pix), marker='o', label='data, roll')
    plt.plot(b, marker='o',label='shifted data')
    if i == 0:
        plt.legend(loc=4,fontsize=12)
    plt.ylim(-1,10)
    ax = plt.gca()
    ax.text(0.10,0.80,'shift %d pix' % i, transform=ax.transAxes)
Run Code Online (Sandbox Code Playgroud)

蓝线:班次前的数据
绿线:预期的班次行为
红线:scipy.ndimage.interpolation.shift的实际班次输出

我如何调用函数或我如何理解它的行为是否有一些错误mode = 'wrap'?当前结果与相关scipy教程页面和另一个StackOverflow帖子中的模式参数描述形成对比.代码中是否存在一个错误?

使用的Scipy版本是0.18.1,分布在anaconda-2.2.0中

在此输入图像描述

Rad*_*dek 1

您观察到的行为似乎是故意的。

问题的原因在于 C 函数map_coordinate将移位后的坐标转换为移位前的坐标:

map_coordinate(double in, npy_intp len, int mode)
Run Code Online (Sandbox Code Playgroud)

该函数用作执行NI_ZoomShift实际移位的子例程。它有趣的部分如下所示:

在此输入图像描述

例子output = shift(np.arange(10), shift=4, mode='wrap')让我们看看(问题)的输出是如何计算的。

NI_ZoomShiftoutput[0]以某种特殊的方式计算边缘值output[9],所以让我们看一下计算output[1](有点简化):

# input  =         [0,1,2,3,4,5,6,7,8,9]
# output = [ ,?, , , , , , , , ]          '?' == computed position
# shift  = 4
output_index = 1

in  = output_index - shift    # -3
sz  = 10 - 1                  # 9
in += sz * ((-5 / 9) + 1)
#  +=  9 * ((     0) + 1) == 9
# in == 6

return input[in]  # 6 
Run Code Online (Sandbox Code Playgroud)

很明显,这sz = len - 1对您所观察到的行为负责。它是从sz = len2007 年的一个暗示性命名的提交中更改的:修复 ndimage 边界例程中的关闭错误。更新测试。

我不知道为什么要引入这样的改变。我想到的一种可能的解释如下:

函数“shift”使用样条线进行插值。区间上均匀样条的结向量[0, k]很简单[0,1,2,...,k]。当我们说样条线应该环绕时,很自然地要求 和 的值相等0k以便样条线的许多副本可以粘合在一起,形成周期函数:

0--1--2--3-...-k              0--1--2--3-...-k              0--1-- ...
               0--1--2--3-...-k              0--1--2--3-...-k      ...
Run Code Online (Sandbox Code Playgroud)

也许shift只是将其输入视为样条线结的值列表?