简体   繁体   English

正确使用numpy的卷积与图像

[英]Correctly using the numpy's convolve with an image

I was watching Andrew Ng's videos on CNN and wanted to to convolve a 6 x 6 image with a 3 x 3 filter. 我正在CNN上观看Andrew Ng的视频,并希望将3 x 3滤镜的6 x 6图像卷积。 The way I approached this with numpy is as follows: 我用numpy进行处理的方式如下:

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

convolved = np.convolve(image, filter)

Running this gives an error saying: 运行此命令将显示错误消息:

ValueError: object too deep for desired array

I could comprehend from the numpy documentation of convolve on how to correctly use the convolve method. 我可以从volve的numpy文档中了解如何正确使用convolve方法。

Also, is there a way I could do a strided convolutions with numpy? 另外,有没有办法用numpy进行大步卷积?

np.convolve function, unfortunately, only works for 1-D convolution. 不幸的是, np.convolve函数仅适用于一维卷积。 That's why you get an error; 这就是为什么您会得到一个错误; you need a function that allows you to perform 2-D convolution. 您需要一个可以执行二维卷积的函数。

However , even if it did work, you actually have the wrong operation. 但是 ,即使它确实起作用,您实际上也会执行错误的操作。 What is called convolution in machine learning is more properly termed cross-correlation in mathematics. 机器学习中所谓的卷积在数学上更恰当地称为互相关 They're actually almost the same; 它们实际上几乎是相同的。 convolution involves flipping the filter matrix followed by performing cross-correlation. 卷积涉及翻转滤波器矩阵,然后执行互相关。

To solve your problem, you can look at scipy.signal.correlate (also, don't use filter as a name, as you'll shadow the inbuilt function): 要解决您的问题,您可以查看scipy.signal.correlate (同样,不要使用filter作为名称,因为您将scipy.signal.correlate内置函数):

from scipy.signal import correlate

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

correlate(image, f)

Output: 输出:

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.]])

This is the standard setting of full cross-correlation. 这是完全互相关的标准设置。 If you want to remove elements which would rely on the zero-padding , pass mode='valid' : 如果要删除依赖零填充的元素,请通过mode='valid'

from scipy.signal import correlate

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

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

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM