【发布时间】:2019-02-07 22:47:48
【问题描述】:
目前正在通过 stanford CS131 的免费在线课程学习计算机视觉和机器学习。遇到了一些繁重的数学公式,想知道是否有人可以向我解释如何在只知道图像高度、宽度和内核高度和宽度的情况下为卷积算法实现一个简单的 4 嵌套 for 循环。通过在线研究,我能够提出这个解决方案。
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 个嵌套的 for 循环是如何做到的。如果可以的话,把公式分解成比网上找到的给定数学方程更容易理解的东西。
编辑: 只是为了澄清我留下的代码 sn-p 在一定程度上有效,我正在尝试提出一个优化程度较低且对初学者更友好的解决方案,例如这段代码所要求的:
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
【问题讨论】:
-
首先,尝试手动操作。
标签: python image-processing scipy computer-vision convolution