scipy.interpolate插值方法实例讲解
作者:tony365 发布时间:2022-08-08 21:23:05
标签:scipy.interpolate,插值
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 plt
from scipy.interpolate import griddata, RegularGridInterpolator, Rbf
if __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 * 20
z = (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 data
xnew_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 new
ynew = ynew_edges[:-1, :-1] + np.diff(ynew_edges[0, :2])[0] / 2.
grid_x, grid_y = xnew, ynew
print(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)**2
grid_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 RegularGridInterpolator
def 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()]).T
interp = 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
来源:https://blog.csdn.net/tywwwww/article/details/128474112
0
投稿
猜你喜欢
- 因为工作原因,需要定期清理某个文件夹下面创建时间超过1年的所有文件,所以今天集中学习了一下Python对于本地文件及文件夹的操作。网上 这篇
- 我们经常会遇到数据库磁盘空间爆满的问题,或由于归档日志突增、或由于数据文件过多、大导致磁盘使用紧俏。这里主要说的场景是磁盘空间本身很大,但表
- html<ul class="header-list"> <li v-cl
- Spring @Enable 模块概览框架实现@Enable注解模块激活模块Spring Framework@EnableWebMvcWeb
- 示例from optparse import OptionParser[...]def main():
- 前言使用PyCharm在Python Interpreter设置中的Python虚拟环境安装第三方包时,很有可能报错:Non-zero ex
- 最近在用python做数据统计,这里总结了一些最近使用时查找和总结的一些小技巧,希望能帮助在做这方面时的一些童鞋。有些技巧是很平常的用法,平
- 误区 #28:有关大容量事务日志恢复模式的几个误区28 a)常见的DML操作可以被“最小记录日志” &nb
- MySql 这个数据库绝对是适合dba级的高手去玩的,一般做一点1万篇新闻的小型系统怎么写都可以,用xx框架可以实现快速开发。可是数据量到了
- 本文实例为大家分享了python实现飞机大战游戏的具体代码,供大家参考,具体内容如下1、准备环境下载python(这里建议不需要安装最新的,
- 使用mybatis 从数据库中查询出date 类型字段,在java 类型中只看到了日期,没有看到时分秒,从数据库中是可以看到时分秒的。后来发
- 在实际使用numpy时,我们常常会使用numpy数组的-1维度和”:”用以调用numpy数组中的元素。也经常因为数组的维度而感到困惑。总体来
- 目录一、路由配置二、vue页面嵌套三、嵌套联系一、路由配置const routes = [ { pat
- 脚本调试第一步:设置中断(鼠标左键点击)第二步:输入中断条件(可选功能,鼠标右键点击红点)第三步:触发中断(当符合条件是,中断被触发)出现中
- 本文实例为大家分享了Python实现信息管理系统的具体代码,供大家参考,具体内容如下"""项目名称 =
- python有专门的神经网络库,但为了加深印象,我自己在numpy库的基础上,自己编写了一个简单的神经网络程序,是基于Rosenblatt感
- 需要画框取消注释rectangleimport cv2import os,sys,shutilimport numpy as np# Ope
- 本文代码需要正确安装Python扩展库pywin32,建议下载whl文件进行离线安装。然后调用win32api的ShellExecute()
- 在pandas中的groupby和在sql语句中的groupby有异曲同工之妙,不过也难怪,毕竟关系数据库中的存放数据的结构也是一张大表罢了
- 目录1.列表中存储字典:1.列表中存储多个字典2.访问列表中字典的值3.遍历访问多个值2.字典中存储列表1.访问字典中的列表元素2.访问字典