9

I'm trying to load an image as grayscale as follows:

from skimage import data
from skimage.viewer import ImageViewer

img = data.imread('my_image.png', as_gray=True)

However, if I check for its shape using img.shape it turns out to be a three-dimensional, and not two-dimensional, array. What am I doing wrong?

Tonechas
  • 13,398
  • 16
  • 46
  • 80
rdv
  • 682
  • 2
  • 8
  • 19

1 Answers1

13

From scikit-image documentation, the signature of data.imread is as follows:

skimage.data.imread(fname, as_grey=False, plugin=None, flatten=None, **plugin_args)

Your code does not work properly because the keyword argument as_grey is misspelled (you put as_gray).

Sample run

In [4]: from skimage import data

In [5]: img_3d = data.imread('my_image.png', as_grey=False)

In [6]: img_3d.dtype
Out[6]: dtype('uint8')

In [7]: img_3d.shape
Out[7]: (256L, 640L, 3L)

In [8]: img_2d = data.imread('my_image.png', as_grey=True)

In [9]: img_2d.dtype
Out[9]: dtype('float64')

In [10]: img_2d.shape
Out[10]: (256L, 640L)
Tonechas
  • 13,398
  • 16
  • 46
  • 80
  • 1
    Got it! by the way: is using `data.imread()` to be preferred over `rgb2gray()` from the `rgb2gray` package? – rdv Jun 21 '17 at 11:51
  • 2
    I would have done `img = skimage.io.imread('my_image.png', as_grey=True)` because images that are already in grey-scale format are not converted. If you pass `rgb2gray` an image which is not 3-D or 4-D, you get a ValueError. – Tonechas Jun 21 '17 at 11:59
  • 7
    Alert! - UserWarning: `as_grey` has been deprecated in favor of `as_gray` – pka32 May 11 '19 at 02:18
  • 2
    Fun fact: Grey is the British way of spelling, while Gray is more commonly used among Americans. – A Merii Mar 02 '20 at 09:38