Can I use numpy gradient function with images

4

最近我一直在尝试测试numpy.gradient函数,但是它的行为对我来说有些奇怪。我创建了一个包含随机变量的数组,然后应用了numpy.gradient函数,但是值似乎很疯狂而且不相关。但是使用numpy.diff时,值是正确的。

所以,在查看numpy.gradient文档后,我发现它在所需维度上使用distance=1。

这就是我的意思:

import numpy as np;

a= np.array([10, 15, 13, 24, 15, 36, 17, 28, 39]);
np.gradient(a)
"""
Got this: array([  5. ,   1.5,   4.5,   1. ,   6. ,   1. ,  -4. ,  11. ,  11. ])
"""
np.diff(a)
"""
Got this:  array([  5,  -2,  11,  -9,  21, -19,  11,  11])
"""

我不明白第一个结果中的值是怎么来的。如果默认距离应该是1,那么我应该得到与numpy.diff相同的结果。

是否有人能解释一下这里的距离是什么意思?它是相对于数组索引还是数组中的值?如果它取决于值,那么是否意味着numpy.gradient不能用于图像,因为相邻像素的值差异没有固定值?


3
您可以在 Stack Overflow 上找到已经解决的示例,例如 https://dev59.com/Z2Af5IYBdhLWcg3wcyer, 如果这个不适用于您,还有其他示例。 - user1121588
1
请再仔细查看文档字符串(http://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html)。它解释了`gradient`计算的内容。您可以在维基百科上阅读有关“中心差异”的内容(https://en.wikipedia.org/wiki/Finite_difference; 特别是,https://en.wikipedia.org/wiki/Finite_difference#Forward.2C_backward.2C_and_central_differences)。 - Warren Weckesser
3个回答

6
# load image
img = np.array([[21.0, 20.0, 22.0, 24.0, 18.0, 11.0, 23.0],
                [21.0, 20.0, 22.0, 24.0, 18.0, 11.0, 23.0],
                [21.0, 20.0, 22.0, 24.0, 18.0, 11.0, 23.0],
                [21.0, 20.0, 22.0, 99.0, 18.0, 11.0, 23.0],
                [21.0, 20.0, 22.0, 24.0, 18.0, 11.0, 23.0],
                [21.0, 20.0, 22.0, 24.0, 18.0, 11.0, 23.0],
                [21.0, 20.0, 22.0, 24.0, 18.0, 11.0, 23.0]])
print "image =", img

# compute gradient of image
gx, gy = np.gradient(img)
print "gx =", gx
print "gy =", gy

# plotting
plt.close("all")
plt.figure()
plt.suptitle("Image, and it gradient along each axis")
ax = plt.subplot("131")
ax.axis("off")
ax.imshow(img)
ax.set_title("image")

ax = plt.subplot("132")
ax.axis("off")
ax.imshow(gx)
ax.set_title("gx")

ax = plt.subplot("133")
ax.axis("off")
ax.imshow(gy)
ax.set_title("gy")
plt.show()

感谢您的工作!我想指出,当您保存np.gradient(img)的输出时,顺序应该是gy,gx而不是gx,gy! - jun

1
对于边界点,np.gradient 使用以下公式:
左端点:f'(x) = [f(x+h)-f(x)]/h
右端点:f'(x) = [f(x)-f(x-h)]/h
对于内部点,它使用以下公式: f'(x) = [f(x+h)-f(x-h)]/2h 第二种方法更准确 - O(h^2) vs O(h)。因此在第二个数据点处,np.gradient 将导数估计为 (13-10)/2 = 1.5。
我制作了一段视频,解释了这些数学知识:https://www.youtube.com/watch?v=NvP7iZhXqJQ

0

内部使用中心差分,边界使用一阶差分。

15 - 10
13 - 10 / 2
24 - 15 / 2
...
39 - 28

它在内部应用[-1 0 1]的核,边缘应用[-1 1]。感谢解释。 - Hisham Ragheb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接