背景/上下文
我试图重现ndimage.affine_transformscipy
函数输出的值,但与实现相比,我似乎使用了不同的“三次”插值方案。scipy
例子
让我们看一个非常简单的示例(不是您想要使用三次插值的数据,但易于理解)。为了检查我实施了统一的 Catmull-Rom splines的值。我的小实现示例:
import numpy as np
from scipy.ndimage import affine_transform
def catmull_rom_interp(p0, p1, p2, p3, x):
return (
(-0.5 * p0 + 1.5 * p1 - 1.5 * p2 + 0.5 * p3) * (x ** 3)
+ (p0 - 2.5 * p1 + 2 * p2 - 0.5 * p3) * (x ** 2)
+ (-0.5 * p0 + 0.5 * p2) * x
+ p1
)
image = np.zeros((9,))
image[3] = 13.3
scipy_result_filtered = affine_transform(
image, np.eye(1), offset=-1.7, order=3, prefilter=True
)
scipy_result = affine_transform(image, np.eye(1), offset=-1.7, order=3, prefilter=False)
image_padded = np.pad(image, 3, mode="constant", constant_values=0)
result_manual = np.zeros((9,))
for i in range(9):
result_manual[i] = catmull_rom_interp(*image_padded[i : i + 4], 0.3)
print(scipy_result)
print(scipy_result_filtered)
print(result_manual)
# yields
# [0. 0. 0. 0.05985 4.63061667 7.84921667 0.76031667 0. 0. ]
# [0. 0. 0.1675183 -1.06094923 4.43537861 11.10313479 -1.75261778 0.46923634 -0.12432758]
# [0. 0. 0. -0.41895 3.85035 10.84615 -0.97755 0. 0. ]
#
# PLOTTING
#
import matplotlib.pyplot as plt
plt.gca().grid()
plots = []
for i in range(9):
plots.append(lambda x: catmull_rom_interp(*image_padded[i : i + 4], x))
plt.plot(scipy_result, "--", label="scipy", alpha=0.5)
plt.plot(scipy_result, "o", color=plt.get_cmap("tab10")(0))
plt.plot(scipy_result_filtered, "--", label="scipy filtered", alpha=0.5)
plt.plot(scipy_result_filtered, "o", color=plt.get_cmap("tab10")(1))
plt.plot(result_manual, "o")
for i in range(9):
plt.plot(
np.linspace(i - 0.3, i + 1 - 0.3, 100),
plots[i](np.linspace(0, 1, 100)),
"--",
alpha=0.5,
color=plt.get_cmap("tab10")(2),
label="Catmull-Rom spline" if i == 0 else None,
)
plt.plot(
np.arange(-0.3, 8.8),
[0] * 2 + list(image[:-1]),
"o",
label="Data to interpolate",
color="k",
)
plt.legend(framealpha=1)
plt.show()
将产生以下图(请注意,由于不知道 scipy 函数的真实插值函数,我只是绘制了线性连接以更好地突出不同的数据点):
观察:
- scipy 方法不使用 Catmull-Rom 样条
- scipy 方法(没有过滤)不会产生通常与锐利边缘的三次插值相关的过冲,但正如 scipy 文档中提到的那样确实会导致一些模糊,这似乎也与我在例子
- 预过滤的 scipy 方法更接近于 Catmull-Rom 样条但不完全相同(存在明显差异)
问题
- scipy 使用哪种插值方案?
- 在他们的文档和/或代码中实际在哪里找到它?
- 奖励:在 Python 中实现它(用于检查目的)的简单方法