Skip to main content
 首页 » 编程设计

python之在 Python 中读取图像文件并计算 Canny 边缘过滤器

2025年05月04日21yjmyzz

我想用 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 图像(即彩色图像)。对于此类图像,我们必须先将其转换为灰度图像,然后才能将它们传递给 Canny 边缘检测器,因为 parameter image has to be a 2D array .

image : 2D array
Greyscale input image to detect edges on; can be of any dtype.

这是一个例子:

# 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) 

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