【问题标题】:Read image file in Python and compute Canny edge filters在 Python 中读取图像文件并计算 Canny 边缘过滤器
【发布时间】:2018-07-07 14:02:19
【问题描述】:

我想用 Python 读取图像文件并应用 skimage 的 Canny 边缘过滤器。但我不知道特征计算的正确数组格式。这就是我所拥有的:

from PIL import Image
from skimage import feature

PATH = '/foo/bar.jpg'

import numpy
img = numpy.asarray(Image.open(PATH).convert('LA'))

# apply Canny Edge filters
edges1 = feature.canny(img)
edges2 = feature.canny(img, sigma=3)

功能调用引发此错误:“参数image 必须是二维数组”。如何将 numpy 数组转换为必要的形式?

【问题讨论】:

  • 似乎您正在传递 RGB 图像。您可以通过灰度图像并获得精巧的边缘
  • 只要试着找到错误的根源。 img.shape 将指示数组的维数。你需要像(3000L, 4000L) 这样的东西——那是二维的。如果是(3000L, 4000L, 3L),则您正在处理可能未定义feature.canny 算法的RGB 图像。

标签: python arrays numpy scikit-image canny-operator


【解决方案1】:

根据您的问题描述,您似乎正在处理 RGB 图像(即彩色图像)。对于这样的图像,我们必须首先将其转换为灰度图像,然后才能将它们传递给 Canny Edge Detector,因为parameter image has to be a 2D array

image : 二维数组
用于检测边缘的灰度输入图像;可以是任何数据类型。

这是一个例子:

# load color image
In [12]: img_rgb = 'model.jpg'
In [13]: img_arr = np.array(Image.open(img_rgb), dtype=np.uint8)

In [14]: img_arr.shape
Out[14]: (1005, 740, 3)

# convert to grayscale image
In [15]: from skimage.color import rgb2gray
In [16]: img_gray = rgb2gray(img_arr)

In [17]: img_gray.shape
Out[17]: (1005, 740)

In [18]: edges1 = feature.canny(img_gray)
    ...: edges2 = feature.canny(img_gray, sigma=3)

In [19]: edges1.shape
Out[19]: (1005, 740)

In [20]: edges2.shape
Out[20]: (1005, 740)

# display    
In [21]: plt.imshow(edges1)

我得到的结果如下图所示:

【讨论】:

  • 谢谢,这行得通 :-) 我以为我已经用convert('LA') 方法获得了灰度图像。
猜你喜欢
  • 2021-07-20
  • 2021-12-03
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
  • 2021-07-24
  • 2012-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多