I'd like to read an image file with Python and apply skimage's Canny edge filter. But I don't know the correct array format for the feature computation. That's what I have:
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)
The feature call raises this error: "The parameter image
must be a 2-dimensional array". How do I convert the numpy array to the necessary form?
From the description of your question, it seems that you're dealing with RGB images (i.e. color images). For such images, we have to first convert it to a grayscale image and then only we can pass them to Canny Edge Detector because the parameter image has to be a 2D array.
image
: 2D array
Greyscale input image to detect edges on; can be of any dtype.
Here is an example:
# 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)
And I get the result as in the below image: