首页 > 解决方案 > 如何用 Python 插值向量场?

问题描述

我有一个 2D 向量场(实际上它是 3D,但如果我们知道如何用 2D 来做,我认为它很容易推广到 3D),如下所示:

import matplotlib.pyplot as plt, numpy as np
x = [0, 0, 1, 1, 2, 2, 0, 1, 2]
y = [1, 2, 1, 2, 1, 2, 1.5, 1.5, 1.5]
u = [0.5, -1, 0, 0, 0.25, 1, 0, 0, 0.75]
v = [1, 1, 1, 1, 1, 1, 1, 1, 1]
plt.quiver(x, y, u, v)
plt.show()

在此处输入图像描述

如何平滑地插值这个向量场?

我知道如何使用np.polyfit,但我不知道如何对矢量场进行插值。

示例:我想插入[0,2]x[1,2]数百个箭头。

标签: pythonnumpyvectorinterpolation

解决方案


使用 NumPymeshgrid和 SciPy 的interpolate.griddata方法,这可能是一个快速可行的解决方案:

import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate

x = [0, 0, 1, 1, 2, 2, 0, 1, 2]
y = [1, 2, 1, 2, 1, 2, 1.5, 1.5, 1.5]
u = [0.5, -1, 0, 0, 0.25, 1, 0, 0, 0.75]
v = [1, 1, 1, 1, 1, 1, 1, 1, 1]

plt.figure(1)
plt.quiver(x, y, u, v)

xx = np.linspace(0, 2, 10)
yy = np.linspace(1, 2, 10)
xx, yy = np.meshgrid(xx, yy)

points = np.transpose(np.vstack((x, y)))
u_interp = interpolate.griddata(points, u, (xx, yy), method='cubic')
v_interp = interpolate.griddata(points, v, (xx, yy), method='cubic')

plt.figure(2)
plt.quiver(xx, yy, u_interp, v_interp)
plt.show()

插值图的输出:

输出

玩弄要在np.linspace调用中创建的点数,会给您或多或少的箭头。

希望有帮助!


推荐阅读