Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opencv convert to grayscale not working properly [duplicate]

I've been trying to convert an image to grayscale using opencv in Python but it converts the image to some kind of thermal camera image. What am I doing wrong? Here is the code for image below:

img =X_tr[9999]
plt.imshow(img)
plt.show()
img = cv2.cvtColor(img.astype(np.uint8), cv2.COLOR_RGB2GRAY)
plt.imshow(img)
plt.show()
img.shape

This image is taken from CIFAR10 dataset. Thanks. Code and result after using opencv

like image 834
Neeraj Negi Avatar asked Apr 01 '17 14:04

Neeraj Negi


People also ask

Why do I get a green image when I convert an RGB image to grayscale using OpenCV?

You have to explicitly set the cmap (colormap) parameter to gray , i.e. use plt. imshow(image, cmap='gray') . The default is viridis , obviously some green-ish/blue-ish colormap. Thanks!

How do I convert an image to grayscale in OpenCV?

Method 1: Using the cv2.Import the OpenCV and read the original image using imread() than convert to grayscale using cv2. cvtcolor() function.

What happens when you convert an image to grayscale?

It eliminates every form of colour information and only leaves different shades of gray; the brightest being white and the darkest of it being black. Its intermediate shades usually have an equal level of brightness for the primary colours (red, blue and green).

What is the purpose of cv2 cvtColor () function?

cv2. cvtColor() method is used to convert an image from one color space to another. There are more than 150 color-space conversion methods available in OpenCV.


1 Answers

Gray scale images, i.e. images with only one colorchannel, are interpreted by imshow as to be plotted using a colormap. You therefore need to specify the colormap you want to use (and the normalization, if it matters).

plt.imshow(img, cmap="gray", vmin=0, vmax=255)
like image 96
ImportanceOfBeingErnest Avatar answered Sep 28 '22 02:09

ImportanceOfBeingErnest