目前正在通过斯坦福CS131免费在线课程学习计算机视觉和机器学习。遇到了一些复杂的数学公式,想知道如何仅仅知道图像高度、宽度和卷积核高度、宽度的情况下实现一个简单的四重循环的卷积算法。我在网上研究后得出了这个解决方案。
image_padded = np.zeros((image.shape[0] + 2, image.shape[1] + 2))
image_padded[1:-1, 1:-1] = image
for x in range(image.shape[1]): # Loop over every pixel of the image
for y in range(image.shape[0]):
# element-wise multiplication of the kernel and the image
out[y, x] = (kernel * image_padded[y:y + 3, x:x + 3]).sum()
我能够理解这个算法,因为一些网站使用了这种类型的算法的例子,然而我似乎不能理解如何用4个嵌套的循环来完成它。如果可以的话,请将公式分解为更容易理解的东西,而不是在网上找到的给定数学方程式。
编辑: 只是为了澄清,虽然我留下的代码片段在某种程度上是有效的,但我正在尝试想出一种解决方案,它更少优化,对初学者更友好,就像这段代码所要求的那样:
def conv_nested(image, kernel):
"""A naive implementation of convolution filter.
This is a naive implementation of convolution using 4 nested for-loops.
This function computes convolution of an image with a kernel and outputs
the result that has the same shape as the input image.
Args:
image: numpy array of shape (Hi, Wi)
kernel: numpy array of shape (Hk, Wk)
Returns:
out: numpy array of shape (Hi, Wi)
"""
Hi, Wi = image.shape
Hk, Wk = kernel.shape
out = np.zeros((Hi, Wi))
### YOUR CODE HERE
### END YOUR CODE
return out