文章目录

  • scipy.interpolate插值方法
    • 1 一维插值
    • 2 multivariate data
    • 3 Multivariate data interpolation on a regular grid
    • 4 Rbf 插值方法

scipy.interpolate插值方法

1 一维插值

from scipy.interpolate import interp1d
1维插值算法

from scipy.interpolate import interp1d
x = np.linspace(0, 10, num=11, endpoint=True)
y = np.cos(-x**2/9.0)
f = interp1d(x, y)
f2 = interp1d(x, y, kind='cubic')
xnew = np.linspace(0, 10, num=41, endpoint=True)
import matplotlib.pyplot as plt
plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--')
plt.legend(['data', 'linear', 'cubic'], loc='best')
plt.show()

数据点,线性插值结果,cubic插值结果:

2 multivariate data

from scipy.interpolate import interp2d

from scipy.interpolate import griddata
多为插值方法,可以应用在2Dlut,3Dlut的生成上面,比如当我们已经有了两组RGB映射数据, 可以插值得到一个查找表。

二维插值的例子如下:

import numpy as np
from scipy import interpolate
import matplotlib.pyplot as pltfrom scipy.interpolate import griddata, RegularGridInterpolator, Rbfif __name__ == "__main__":x_edges, y_edges = np.mgrid[-1:1:21j, -1:1:21j]x = x_edges[:-1, :-1] + np.diff(x_edges[:2, 0])[0] / 2.y = y_edges[:-1, :-1] + np.diff(y_edges[0, :2])[0] / 2.# x_edges, y_edges 是 20个格的边缘的坐标, 尺寸 21 * 21# x, y 是 20个格的中心的坐标, 尺寸 20 * 20z = (x + y) * np.exp(-6.0 * (x * x + y * y))print(x_edges.shape, x.shape, z.shape)plt.figure()lims = dict(cmap='RdBu_r', vmin=-0.25, vmax=0.25)plt.pcolormesh(x_edges, y_edges, z, shading='flat', **lims) # plt.pcolormesh(), plt.colorbar() 画图plt.colorbar()plt.title("Sparsely sampled function.")plt.show()# 使用grid dataxnew_edges, ynew_edges = np.mgrid[-1:1:71j, -1:1:71j]xnew = xnew_edges[:-1, :-1] + np.diff(xnew_edges[:2, 0])[0] / 2. # xnew其实是 height newynew = ynew_edges[:-1, :-1] + np.diff(ynew_edges[0, :2])[0] / 2.grid_x, grid_y = xnew, ynewprint(x.shape, y.shape, z.shape)points = np.hstack((x.reshape(-1, 1), y.reshape(-1, 1)))z1 = z.reshape(-1, 1)grid_z0 = griddata(points, z1, (grid_x, grid_y), method='nearest').squeeze()grid_z1 = griddata(points, z1, (grid_x, grid_y), method='linear').squeeze()grid_z2 = griddata(points, z1, (grid_x, grid_y), method='cubic').squeeze()rbf = Rbf(points[:, 0], points[:, 1], z, epsilon=2)grid_z3 = rbf(grid_x, grid_y)plt.subplot(231)plt.imshow(z.T, extent=(-1, 1, -1, 1), origin='lower')plt.plot(points[:, 0], points[:, 1], 'k.', ms=1)plt.title('Original')plt.subplot(232)plt.imshow(grid_z0.T, extent=(-1, 1, -1, 1), origin='lower')plt.title('Nearest')plt.subplot(233)plt.imshow(grid_z1.T, extent=(-1, 1, -1, 1), origin='lower', cmap='RdBu_r')plt.title('Linear')plt.subplot(234)plt.imshow(grid_z2.T, extent=(-1, 1, -1, 1), origin='lower')plt.title('Cubic')plt.subplot(235)plt.imshow(grid_z3.T, extent=(-1, 1, -1, 1), origin='lower')plt.title('rbf')plt.gcf().set_size_inches(8, 6)plt.show()

示例2:

def func(x, y):return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]rng = np.random.default_rng()
points = rng.random((1000, 2))
values = func(points[:,0], points[:,1])from scipy.interpolate import griddata
grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest')
grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear')
grid_z2 = griddata(points, values, (grid_x, grid_y), method='cubic')import matplotlib.pyplot as plt
plt.subplot(221)
plt.imshow(func(grid_x, grid_y).T, extent=(0,1,0,1), origin='lower')
plt.plot(points[:,0], points[:,1], 'k.', ms=1)
plt.title('Original')
plt.subplot(222)
plt.imshow(grid_z0.T, extent=(0,1,0,1), origin='lower')
plt.title('Nearest')
plt.subplot(223)
plt.imshow(grid_z1.T, extent=(0,1,0,1), origin='lower')
plt.title('Linear')
plt.subplot(224)
plt.imshow(grid_z2.T, extent=(0,1,0,1), origin='lower')
plt.title('Cubic')
plt.gcf().set_size_inches(6, 6)
plt.show()

3 Multivariate data interpolation on a regular grid

from scipy.interpolate import RegularGridInterpolator

已知一些grid上的值。
可以应用在2Dlut,3Dlut,当我们已经有了一个多维查找表,然后整个图像作为输入,得到查找和插值后的输出。

二维网格插值方法(好像和resize的功能比较一致)

# 使用RegularGridInterpolator
import matplotlib.pyplot as plt
from scipy.interpolate import RegularGridInterpolatordef F(u, v):return u * np.cos(u * v) + v * np.sin(u * v)fit_points = [np.linspace(0, 3, 8), np.linspace(0, 3, 8)]
values = F(*np.meshgrid(*fit_points, indexing='ij'))ut, vt = np.meshgrid(np.linspace(0, 3, 80), np.linspace(0, 3, 80), indexing='ij')
true_values = F(ut, vt)
test_points = np.array([ut.ravel(), vt.ravel()]).Tinterp = RegularGridInterpolator(fit_points, values)
fig, axes = plt.subplots(2, 3, figsize=(10, 6))
axes = axes.ravel()
fig_index = 0
for method in ['linear', 'nearest', 'linear', 'cubic', 'quintic']:im = interp(test_points, method=method).reshape(80, 80)axes[fig_index].imshow(im)axes[fig_index].set_title(method)axes[fig_index].axis("off")fig_index += 1
axes[fig_index].imshow(true_values)
axes[fig_index].set_title("True values")
fig.tight_layout()
fig.show()
plt.show()

4 Rbf 插值方法

interpolate scattered 2-D data

import numpy as np
from scipy.interpolate import Rbf
import matplotlib.pyplot as plt
from matplotlib import cm# 2-d tests - setup scattered data
rng = np.random.default_rng()
x = rng.random(100) * 4.0 - 2.0
y = rng.random(100) * 4.0 - 2.0
z = x * np.exp(-x ** 2 - y ** 2)edges = np.linspace(-2.0, 2.0, 101)
centers = edges[:-1] + np.diff(edges[:2])[0] / 2.XI, YI = np.meshgrid(centers, centers)
# use RBF
rbf = Rbf(x, y, z, epsilon=2)
Z1 = rbf(XI, YI)points = np.hstack((x.reshape(-1, 1), y.reshape(-1, 1)))
Z2 = griddata(points, z, (XI, YI), method='cubic').squeeze()# plot the result
plt.figure(figsize=(20,8))
plt.subplot(1, 2, 1)
X_edges, Y_edges = np.meshgrid(edges, edges)
lims = dict(cmap='RdBu_r', vmin=-0.4, vmax=0.4)
plt.pcolormesh(X_edges, Y_edges, Z1, shading='flat', **lims)
plt.scatter(x, y, 100, z, edgecolor='w', lw=0.1, **lims)
plt.title('RBF interpolation - multiquadrics')
plt.xlim(-2, 2)
plt.ylim(-2, 2)
plt.colorbar()plt.subplot(1, 2, 2)
X_edges, Y_edges = np.meshgrid(edges, edges)
lims = dict(cmap='RdBu_r', vmin=-0.4, vmax=0.4)
plt.pcolormesh(X_edges, Y_edges, Z2, shading='flat', **lims)
plt.scatter(x, y, 100, z, edgecolor='w', lw=0.1, **lims)
plt.title('griddata - cubic')
plt.xlim(-2, 2)
plt.ylim(-2, 2)
plt.colorbar()
plt.show()

得到结果如下, RBF一定程度上和 griddata可以互用, griddata方法比较通用


[1]https://docs.scipy.org/doc/scipy/tutorial/interpolate.html

scipy.interpolate插值方法介绍相关推荐

  1. scipy.interpolate: 插值和平滑处理

    scipy有很多插值函数(方法),按维度可分为一维.二维和多维的插值方法,按方法包括拉格朗日和泰勒插值方法等,具体插值函数可参阅如下介绍: https://docs.scipy.org/doc/sci ...

  2. python插值(scipy.interpolate模块的griddata和Rbf)

    1.插值scipy.interpolate SciPy的interpolate模块提供了许多对数据进行插值运算的函数,范围涵盖简单的一维插值到复杂多维插值求解. 一维插值:当样本数据变化归因于一个独立 ...

  3. 成功解决AttributeError: type object 'scipy.interpolate.interpnd.array' has no attribute '__reduce_cython

    成功解决AttributeError: type object 'scipy.interpolate.interpnd.array' has no attribute '__reduce_cython ...

  4. 成功解决ImportError: cannot import name ‘spline‘ from ‘scipy.interpolate‘—利用make_interp_spline函数绘制平滑的曲线

    成功解决ImportError: cannot import name 'spline' from 'scipy.interpolate'-利用make_interp_spline函数绘制平滑的曲线 ...

  5. 如何优雅地平均多条曲线 scipy.interpolate.interp1d below the interpolation range error

    正确的思路应该是得到所有曲线,然后规定新曲线采样位置(x坐标),然后平均y值.下面的做法错了,因为ROC曲线上的任一个点的位置是清晰地定义好的,插值是画蛇添足. ------------------- ...

  6. 对scipy.interpolate.make_interp_spline的理解

    问题描述 记录今天看见代码里面用到scipy.interpolate.make_interp_spline()函数,主要学习https://blog.csdn.net/weixin_42782150/ ...

  7. python interpolate.interp1d_我如何使用scipy.interpolate.interp1d使用相同的X数组插值多个Y数组?...

    例如,我有一个二维数据数组,其中一个维度上带有误差条,如下所示: In [1]: numpy as np In [2]: x = np.linspace(0,10,5) In [3]: y = np. ...

  8. scipy.interpolate插值

    python  SciPy库依赖于NumPy,提供了便捷且快速的N维数组操作. 可以实现插值,积分,优化,图像处理,特殊函数等等操作. 参考官方文档: Interpolation (scipy.int ...

  9. matlab griddata插值太慢,非常慢的插值使用`scipy.interpolate.griddata`

    在长期忍受scipy.interpolate.griddata极其缓慢的性能之后,我决定放弃{ 所以对于上面的例子,上面问题中的那个,你可以得到输入文件here,这是一段需要1.1ms的代码,而在上面 ...

最新文章

  1. Linux后台开发必看!
  2. java亲密数的解题思路,算法解题思路总结 - jjhgx的个人空间 - OSCHINA - 中文开源技术交流社区...
  3. python已经取代了excel_Python已经取代Excel?网友:笑了
  4. Spark入门(Python)
  5. 微信小程序scroll-view去除滚动条 (安卓、ios都有效)
  6. As-If-Serial 理解
  7. 非常好的Oracle基础教程
  8. 新电脑java开发常用环境安装下载教程收集--持续更新
  9. 【免费】自动检测删除微信好友教程 微信一键清死粉
  10. arcgis 去除影像黑色边框(nodata)
  11. 电气火灾监控系统在地铁供配电系统中的应用
  12. mysql 错误代码1130_mysql出现错误码1130怎么办
  13. php mp3播放列表,ubuntu的本地MP3音乐播放器mpd+mpc
  14. Description Resource Path Location Type Cannot change version of project fac(导入maven项目出现红叉问题)...
  15. 【无标题】 R语言下载keras最新方法
  16. PAT B1033旧键盘打字
  17. 一份不悔的爱情 魔兽中那些我们追过的橙色武器
  18. 服务器不稳定怎么解决?常见的4种问题和6种处理方法
  19. 为什么安装一些程序需要VC++运行库
  20. 【Unity Shader】Unity中阴影走样的解决方案

热门文章

  1. C语言程序设计getint,getint函数解决方案
  2. 域控制器组策略:统一修改用户计算机桌面壁纸
  3. 获取别的小程序路径方法
  4. activiti个人任务分配,UEL表达式,监听器分配,任务查询
  5. Mars3D认识与理解
  6. 【ROS】针对ROS安装过程中出现rosdep update超时问题的解决方法
  7. FTP连接 出现200 Type set to A. 227 Entering Passive Mode
  8. CSS3旋转动画(平滑,无限循环)
  9. 70天的JQUERY学习: 选择器+事件+效果。总结篇
  10. 第一行代码-第二版(郭霖著)笔记六(持久化技术)