Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

opencv convert image to grayscale, and display using matplotlib gives strange color [duplicate]

I see an oddness when loading an image using opencv, convert to grayscale, and plot using matplotlib:

from matplotlib import pyplot as plt
import argparse
import cv2

image = cv2.imread("images/image1.jpg")
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
plt.imshow(image)

Just that simple.

But it gives a "grayscale" plot as follows:

Anything wrong ? Many thanks! enter image description here

like image 429
captainst Avatar asked Dec 24 '22 04:12

captainst


2 Answers

It's because of the way Matplotlib maps single-channel output. It defaults to the "perceptially uniform" colourmap: blue->yellow; a bit like how you might expect a heatmap to be from blue to red, but theoretically clearer for human vision.

There's some more details here that might help: https://matplotlib.org/users/colormaps.html

You need to tell it to use the gray colourmap when you show the image:

plt.imshow(arr, cmap='gray')

Also see this question: Display image as grayscale using matplotlib

Edit: Also, see lightalchemist's answer regarding mixing up RGB and BGR!

like image 136
n00dle Avatar answered May 30 '23 14:05

n00dle


OpenCV reads in images in the order BGR so you should convert

image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

Secondly, what you are seeing is Matplotlib displaying the image intensities as a heatmap. Just pass the desired color map to its cmap argument

plt.imshow(image, cmap=plt.cm.gray)
like image 21
lightalchemist Avatar answered May 30 '23 14:05

lightalchemist