python - 生成二维数组的梯度图

标签 python numpy

我有一个二维数组,它存储每个点的属性值作为它的元素:f(x,y) = f[x][y]。现在我想找到这个数组的梯度。我查看了 np.gradient 但它只给出了两个数组作为返回值,第一个是 x 方向的导数,第二个是 y 方向的导数。

我想了解如何使用此方法或任何其他方法来创建显示二维数组梯度变化的梯度图。
varray 是我要为其创建渐变图的二维数组。以下是我现在唯一能想到的。我知道应该有聪明的方法来使用 np.gradient() 生成的 x gradienty gradient 但我想不出。 lxly 是二维数组的 x 和 y 维度。

vgrad = np.gradient(varray)
xgrad = vgrad[0]
x, y = range(0, lx), range(0,ly)
xi, yi = np.meshgrid(x, y)
rbf = scipy.interpolate.Rbf(xi, yi, xgrad)
plt.imshow(v, vmin = np.amin(xgrad), vmax=np.amax(xgrad))
plt.colorbar()
plt.show()  

我基本上想从第一张图片中获取第二张图片。第二张图片被描述为 σ =\alpha*grad(varray)

使用下面@Mad Physicist 建议的梯度大小。

vgrad = np.gradient(varray)
fulgrad = np.sqrt(vgrad[0]**2 + vgrad[1]**2)
plt.imshow(fulgrad,cmap=plt.get_cmap('hot'), vmin = np.amin(fulgrad),vmax = np.amax(fulgrad))  
plt.colorbar()
plt.show()  

我得到的图像: enter image description here

我是根据对等式的基本理解来解释这个错误的吗?

这是我的图片。左侧:初始 2D map 的图像。右侧:渐变图的图像。 @Mad Physicist 你认为它们和上面的相似,只是颜色不同吗?

enter image description here enter image description here

最佳答案

如果你正在寻找梯度的大小,你可以这样做

mag = np.sqrt(vgrad[0]**2 + vgrad[1]**2)

然后绘制 mag 而不是上面的 xgrad。如果您想将梯度绘制为矢量图或流图,请执行以下操作

plt.streamplot(xi, yi, vgrad[0], vgrad[1])

您可能还对仅通过在 3D 中绘制原始表面即可获得的斜率的视觉表示感兴趣:

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(xi, yi, varray)
plt.show()

参见 What is the equivalent of Matlab's surf(x,y,z,c) in matplotlib?http://matplotlib.org/examples/mplot3d/surface3d_demo.html

关于python - 生成二维数组的梯度图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34003993/

相关文章:

c++ - 什么是使用 opencv::Mat 优化 c++ 矩阵计算

python - 如何根据数组中值的相对大小将 numpy 数组排序为由单独列表指定的特定顺序

Python - 使用多个值模拟对象的属性?

python - 如何允许用户在 Django 中更改自己的密码?

python - 使用 ANTLR 用 Python 解析一些 Java 代码

python - 如何从内存中解码jpg图像?

python - sympy 中有多个用于 lambdify 的模块

python - python中的回归系数计算

python - 在Python中选择性地删除字符串后面的空格

python - 在python中迭代和匹配大文件