【问题标题】:Applying a filter on an image with Python使用 Python 对图像应用过滤器
【发布时间】:2019-05-22 05:56:46
【问题描述】:

这是我的代码:

from matplotlib.pyplot import imread
import matplotlib.pyplot as plt
from scipy.ndimage.filters import convolve


k3 = np.array([ [-1, -1, -1], [-1, 8, -1], [-1, -1, -1] ])
img = imread("lena.jpg")
channels = []
for channel in range(3):
    res = convolve(img[:,:,channel], k3)
    channels.append(res)

img = np.dstack((channels[0], channels[1], channels[2]))
plt.imshow(img)
plt.show()

k3 过滤器假设是一个边缘检测过滤器。相反,我得到一个奇怪的图像,看起来像白噪声。

为什么?

这是输出:

【问题讨论】:

  • 你考虑过np.convolve吗? python中的for循环很慢。没有办法解决这个问题,除非不使用它们。我怀疑您可以使用 3 通道内核运行卷积并将其加速 1000 倍
  • 1.可能是由于dtype。如果将 img_filtered 转换为 uint8 (img_filtered.astype(np.uint8)) 会发生什么?
  • 它没有帮助。请看我的编辑
  • 好吧,我不确定您的过滤器设置是否有问题。为了检测边缘,我曾经将内核设置如下。 [[0, 1, 0], [-1, 0, 1], [0, -1, 0]] 顺便说一下,我的图只有四个连接,没有诊断像素。
  • @Sean,基本上,它是为了教育目的而完成的,所以数字对我来说并不重要。不过,我的代码似乎有问题

标签: python-3.x numpy matplotlib image-processing data-science


【解决方案1】:

img 可能是一个 8 位无符号整数。像您一样使用拉普拉斯掩码进行卷积,输出值可能会超出 [0,255] 的有效范围。例如,当为这样的图像分配 -1 时,写入的值将是 254。这导致输出如问题所示。

使用此特定过滤器,首先将图像转换为有符号类型很重要,例如 16 位有符号整数或浮点类型。

img = img.astype(np.int16)

PS:注意Laplace is not an edge detector!

【讨论】:

    猜你喜欢
    • 2020-10-16
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 2021-06-27
    相关资源
    最近更新 更多