使用scipy.interpolate.RectBivariateSpline upscale数据无插值效果求助
问题
使用scipy.interpolate.RectBivariateSpline和interp2d对数据做upscale提升分辨率时,结果未实际插值,仅得到填充大量零的更大矩阵,同时希望原始数据能在新矩阵中居中。
原始代码
生成测试数据
import numpy as np import matplotlib.pyplot as plt import scipy.interpolate n = 10 smile = np.zeros((n,n)) a = 0.5 smile[2,2] = a smile[3,2] = a smile[2,7] = a smile[3,7] = a smile[6,2] = a smile[6,7] = a smile[7,3:7] = a plt.imshow(smile) plt.show()
RectBivariateSpline插值代码
# 生成插值函数 x = np.arange(n) y = x z = smile interpolation_funk = scipy.interpolate.RectBivariateSpline(x,y,z) # 使用插值 x_new = np.arange(2*n) y_new = x_new Z_new = interpolation_funk(x_new,y_new) # 绘制新结果 plt.imshow(Z_new) plt.show()

问题原因
- 坐标范围超出原始数据:原始数据的x/y范围是
[0, 9](共10个点),但新生成的x_new/y_new是[0, 19],超出原始范围的部分,RectBivariateSpline默认外插补0,导致大部分区域都是零。 - 未在原始范围内生成密集采样点:upscale的核心是在原始数据的范围内生成更密集的坐标点,而非扩大坐标范围。
解决方法
方法一:在原始范围内插值实现upscale
直接在原始x/y范围内生成2倍密度的点,得到原始数据的高分辨率插值结果:
import numpy as np import matplotlib.pyplot as plt import scipy.interpolate n = 10 smile = np.zeros((n,n)) a = 0.5 smile[2,2] = a smile[3,2] = a smile[2,7] = a smile[3,7] = a smile[6,2] = a smile[6,7] = a smile[7,3:7] = a # 生成插值函数 x = np.arange(n) y = x z = smile interpolation_funk = scipy.interpolate.RectBivariateSpline(x, y, z) # 在原始范围内生成2倍密集的点 x_new = np.linspace(x.min(), x.max(), 2*n) y_new = np.linspace(y.min(), y.max(), 2*n) # 指定grid=True生成二维网格插值结果 Z_new = interpolation_funk(x_new, y_new, grid=True) plt.figure(figsize=(10,5)) plt.subplot(121) plt.imshow(smile) plt.title('原始数据') plt.subplot(122) plt.imshow(Z_new) plt.title('2倍分辨率插值结果') plt.show()
方法二:让原始数据居中并扩大画布
若要将原始数据放在20x20画布中间,可调整插值坐标范围,结合外插实现居中效果:
# 生成插值函数 x = np.arange(n) y = x z = smile # 选用线性插值避免外插出现异常波动,可根据需求调整阶数 interpolation_funk = scipy.interpolate.RectBivariateSpline(x, y, z, kx=1, ky=1) # 新坐标范围:让原始0-9区域处于20x20画布中间 x_new = np.linspace(-4.5, 14.5, 2*n) y_new = np.linspace(-4.5, 14.5, 2*n) Z_new = interpolation_funk(x_new, y_new, grid=True) plt.figure(figsize=(10,5)) plt.subplot(121) plt.imshow(smile) plt.title('原始数据') plt.subplot(122) plt.imshow(Z_new) plt.title('居中的2倍画布插值结果') plt.show()
补充说明
RectBivariateSpline默认外插为0,若需自定义外插行为,可设置extrapolate参数(如extrapolate=True使用样条外插,或传入自定义函数)。- 调用插值函数时,必须指定
grid=True才能生成二维网格数据,否则会返回一维点的插值结果。
内容的提问来源于stack exchange,提问作者Albert bayazidi
相关产品推荐
相关产品推荐

