正确使用 numpy 的图像卷积

Correctly using the numpy's convolve with an image

我在看 Andrew Ng's videos on CNN 并想用 3 x 3 过滤器对 6 x 6 图像进行卷积。我用 numpy 处理这个问题的方法如下:

image = np.ones((6,6))
filter = np.ones((3,3))

convolved = np.convolve(image, filter)

运行 这给出了一个错误说:

ValueError: object too deep for desired array

我可以从 numpy documentation of convolve 中理解如何正确使用 convolve 方法。

此外,有没有办法用 numpy 进行跨步卷积?

不幸的是,

np.convolve 函数仅适用于 1-D 卷积。这就是你出错的原因;你需要一个允许你执行二维卷积的函数。

但是,即使成功了,其实是你操作错了。机器学习中所谓的卷积在数学中更恰当地称为互相关。它们实际上几乎相同;卷积涉及翻转滤波器矩阵,然后执行互相关。

要解决您的问题,您可以查看 scipy.signal.correlate(另外,不要使用 filter 作为名称,因为您会隐藏内置函数):

from scipy.signal import correlate

image = np.ones((6, 6))
f = np.ones((3, 3))

correlate(image, f)

输出:

array([[1., 2., 3., 3., 3., 3., 2., 1.],
       [2., 4., 6., 6., 6., 6., 4., 2.],
       [3., 6., 9., 9., 9., 9., 6., 3.],
       [3., 6., 9., 9., 9., 9., 6., 3.],
       [3., 6., 9., 9., 9., 9., 6., 3.],
       [3., 6., 9., 9., 9., 9., 6., 3.],
       [2., 4., 6., 6., 6., 6., 4., 2.],
       [1., 2., 3., 3., 3., 3., 2., 1.]])

这是全互相关的标准设置。如果要删除 rely on the zero-padding 的元素,请传递 mode='valid':

from scipy.signal import correlate

image = np.ones((6, 6))
f = np.ones((3, 3))

correlate(image, f, mode='valid')

输出:

array([[9., 9., 9., 9.],
       [9., 9., 9., 9.],
       [9., 9., 9., 9.],
       [9., 9., 9., 9.]])