【问题标题】:Edge detection not working as expected边缘检测未按预期工作
【发布时间】:2018-01-06 10:48:01
【问题描述】:

我只是在 SciPy 和 Python 中玩转卷积和内核。我使用以下内核进行边缘检测,因为它列在 this wikipedia article:



这是我使用的图像:


我得到的结果非常令人失望:

我用于卷积的代码:

edge = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])
results = sg.convolve(img, edge, mode='same')
results[results > 255] = 255
results[results < 0] = 0

...以及我用来读取图像的代码:

img = np.array(Image.open('convolution_test/1.jpg'))
img = img[:, :, 0]

为什么我会得到这些糟糕的结果?

TIA。

【问题讨论】:

  • img 的类型是什么。因为如果它是无符号的,这可能会导致下溢。
  • 如果将矩阵加载为无符号整数,则结果可能会环绕,使得负数实际上是白色值。
  • 但是scipy.convolve 只适用于一维数组?
  • @WillemVanOnsem 非常感谢!我检查了img 数组的数据类型,你是对的......它是uint8。我把它改成了int32,瞧!如果您将评论写为答案,我会接受。 :)
  • @WillemVanOnsem scipy.signal.convolve 也适用于矩阵。我查过了。

标签: python image-processing scipy convolution


【解决方案1】:

我认为问题在于您的图像使用 unsigned 整数。因此,例如,如果您从零中减去 1,您会得到 0-1 = 255 对应的 uint8,因此您会在实际应该是黑色的地方得到白色。

但是,您可以通过使用有符号整数(最好有更深的深度)轻松克服这个问题。例如:

from PIL import Image
import numpy as np
import scipy.signal as sg

img = np.array(Image.open('convolution_test/1.jpg'))
img = img[:, :, 0]
img = img.astype(np.int16)

edge = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])
results = sg.convolve(img, edge, mode='same')
results[results > 255] = 255
results[results < 0] = 0

results = results.astype(np.uint8)

对我来说,这会生成以下图像:

【讨论】:

  • 谢谢 Willi'a'm :p
猜你喜欢
  • 2015-03-09
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 2017-08-20
  • 1970-01-01
相关资源
最近更新 更多