25

When I tried to convert the image to gray scale using:

from skimage.io import imread
from skimage.color import rgb2gray
mountain_r = rgb2gray(imread(os.getcwd() + '/mountain.jpg'))

#Plot
import matplotlib.pyplot as plt
plt.figure(0)
plt.imshow(mountain_r)
plt.show()

I got a weird colored image instead of a gray scale.

Manually implementing the function also gives me the same result. The custom function is:

def rgb2grey(rgb):
    if len(rgb.shape) is 3:
        return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])

    else:
        print 'Current image is already in grayscale.'
        return rgb

Original

Coloured image that is not in greyscale. gray

Why doesn't the function convert the image to greyscale?

kwotsin
  • 2,882
  • 9
  • 35
  • 62
  • 8
    The grayscale-conversion is working correctly, but matplotlib is just using another colormap by default, where not shades of grey, but something between blue and red is chosen. Try ```imshow(cmap='Greys')```. You can check the output and will see, that the lightest parts of the image are currently red, the darkest are blue. – sascha Oct 01 '16 at 12:18
  • That was very helpful. My image is in greyscale now. – kwotsin Oct 01 '16 at 14:17

1 Answers1

39

The resulting image is in grayscale. However, imshow, by default, uses a kind of heatmap (called viridis) to display the image intensities. Just specify the grayscale colormap as shown below:

plt.imshow(mountain_r, cmap="gray")

For all the possible colormaps, have a look at the colormap reference.

Tony Power
  • 1,033
  • 11
  • 23