python - 与水平内核卷积会产生奇怪的输出
问题描述
所以我正在尝试使用看起来像这样的 3x3 水平内核来执行 2D 图像卷积,
horizontal = np.array([
[0, 0, 0],
[-1, 0, 1],
[0, 0, 0]]),
所以我使用下面的卷积函数,我在图像中循环,首先忽略前几个像素(内核的大小)并相乘和相加,
def perform_convolution(k_h, k_w, img_h, img_w, kernel, picture):
# k_w = kernel width, k_h = kernel_height
# img_h = image height, img_w = image width
conv = np.zeros(picture.shape)
for i in range(k_h, img_h - (k_h)):
for j in range(k_w, img_w - (k_w)):
tot = 0
for m in range(k_h):
for n in range(k_w):
tot = tot + kernel[m][n] * picture[i - (k_h) + m][j - (k_w) + n]
conv[i][j] = tot
return conv
但是我得到的输出是完全奇怪的,如下所示
或者,通过使用 PIL 的内核,我得到了这样一个适当的模糊图像,
那么谁能帮我弄清楚我哪里出错了?
我已经用盒子内核尝试了相同的功能,它工作得很好,但我无法弄清楚为什么它的输出如此奇怪。
我也尝试过分离 RGB 波段并分别对它们进行卷积,但没有结果。
原图是这个,
解决方案
Firstly the filter you are using is a gradient filter, which in this case is giving values in the range of [-255,255]. Here the main point to consider is that the value you are getting is not just magnitude, you are also pocking the direction of the edge. So, to account for this you can store the phase information i.e 0 degrees for positive value, 180 degrees for a negative value in another image. Finally while visualizing the gradient image, you can simply have a look at the magnitude of the image and know that a phase image exists that determines the direction of the gradient.
Secondly, the slightly smoothened image you are showing in the question can not be created with this kernel.
Also as a rule of thumb, when you want to apply smooth filter always make sure to have the sum of all elements in the kernel as 1.
推荐阅读
- python-3.x - 如何检查数据框中列标题中的 Nan 值
- python - 如何使用python仅以json格式检索与平台mac关联的id和name
- soap - JAXB unmarshaller 返回字段的默认值
- e2e-testing - 我们如何避免使用 WebdriverIO 同时运行多个测试的竞争条件?
- javascript - 仅当我的对象具有特定字段时如何更新
- matrix - 如何为 Power bi 多级矩阵图设置相等的列宽
- ios - 未检测到某些视图的可访问性,但检测到超级视图
- java - 上传的 GIF 图片不动
- vert.x - 访问静态文件导致“Connection reset by peer”异常
- android - 某些手机的 JavascriptInterface 无法正常工作