首先,让我稍微改一下你的问题:
为什么scipy.ndimage 的 Sobel 运算符版本似乎与 Wikipedia 上给出的定义相反?
这是一个并排比较以显示差异。对于输入,我们使用维基百科文章中的自行车图片:http://en.wikipedia.org/wiki/File:Bikesgray.jpg
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage as ndimage
# Note that if we leave this as unsigned integers we'll have problems with
# underflow anywhere the gradient is negative. Therefore, we'll cast as floats.
z = ndimage.imread('Bikesgray.jpg').astype(float)
# Wikipedia Definition of the x-direction Sobel operator...
kernel = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]], dtype=float)
sobel_wiki = ndimage.convolve(z, kernel)
# Scipy.ndimage version of the x-direction Sobel operator...
sobel_scipy = ndimage.sobel(z, axis=1)
fig, axes = plt.subplots(figsize=(6, 15), nrows=3)
axes[0].set(title='Original')
axes[0].imshow(z, interpolation='none', cmap='gray')
axes[1].set(title='Wikipedia Definition')
axes[1].imshow(sobel_wiki, interpolation='none', cmap='gray')
axes[2].set(title='Scipy.ndimage Definition')
axes[2].imshow(sobel_scipy, interpolation='none', cmap='gray')
plt.show()
请注意,这些值被有效地翻转了。
这背后的逻辑是 Sobel 滤波器基本上是一个梯度算子(numpy.gradient 等价于与[1, 0, -1] 的卷积,除了边缘)。维基百科中给出的定义给出了梯度的数学定义的否定。
例如,numpy.gradient 给出与scipy.ndimage 的 Sobel 过滤器相似的结果:
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage as ndimage
z = ndimage.imread('/home/jofer/Bikesgray.jpg').astype(float)
sobel = ndimage.sobel(z, 1)
gradient_y, gradient_x = np.gradient(z)
fig, axes = plt.subplots(ncols=2, figsize=(12, 5))
axes[0].imshow(sobel, interpolation='none', cmap='gray')
axes[0].set(title="Scipy's Sobel")
axes[1].imshow(gradient_x, interpolation='none', cmap='gray')
axes[1].set(title="Numpy's Gradient")
plt.show()
因此,scipy.ndimage 使用的约定与我们对数学梯度的期望一致。
快速旁注:通常所说的“sobel 滤波器”实际上是从两个 sobel 滤波器沿不同轴计算得出的梯度幅度。在scipy.ndimage 中,您可以这样计算:
import matplotlib.pyplot as plt
import scipy.ndimage as ndimage
z = ndimage.imread('/home/jofer/Bikesgray.jpg').astype(float)
sobel = ndimage.generic_gradient_magnitude(z, ndimage.sobel)
fig, ax = plt.subplots()
ax.imshow(sobel, interpolation='none', cmap='gray')
plt.show()
在这种情况下使用哪种约定也无关紧要,因为重要的是输入梯度的绝对值。
无论如何,对于大多数用例,具有可调节窗口的更平滑的梯度过滤器(例如ndimage.gaussian_gradient_magnitude)是边缘检测的更好选择。