4

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

captainst
  • 617
  • 1
  • 7
  • 20

2 Answers2

7

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)
lightalchemist
  • 10,031
  • 4
  • 47
  • 55
6

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!

n00dle
  • 5,949
  • 2
  • 35
  • 48