JDK JDK - 4 months ago 11
Python Question

rgb2gray not working, creating rainbow image

I'm trying to do data analysis on a series of photos, and when all photos are "changed" to grayscale from RGB, they are coming up as, well look:

The standard Astronaut image as my system says it's grayscale

Here's the code I'm using:

import matplotlib.pyplot as plt
from skimage.color import rgb2gray
from skimage import data
img = data.astronaut()
img_gray = rgb2gray(img)

plt.imshow(img_gray)
plt.show()


I also tried converting as hsv to rgb then grayscale, but it still produces a similar, non-grayscale image.

Answer

The problem is that matplotlib shows the image 2D with its default colormap. Change your code to

import matplotlib.pyplot as plt
from skimage.color import rgb2gray
from skimage import data
img = data.astronaut()
img_gray = rgb2gray(img)

plt.imshow(img_gray, cmap='gray')
plt.show()

You can also use

from skimage import io
io.imshow(img_gray)

which will handle grayscale images automatically

Comments