1
votes

I am loading an image using cv2 in python (jupyter lab) and trying to display a grayscale image using plt.imshow.

import cv2
import matplotlib.pyplot as plt

img = cv2.imread('my_image.jpg')
new_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(new_img, cv2.COLOR_RGB2GRAY)
plt.imshow(img)
plt.imshow(new_img)
plt.imshow(gray)

When the code above is run this happens:

  • img is distored in colors (as expected)
  • new_img has the "correct" colors
  • gray is some wierd distorted colors

My question is regarding the gray image. Why does this happen and how can I change it?

1
Just use grey = cv2.imread("...", cv2.IMREAD_GRAYSCALE) which will be faster and take less RAM.Mark Setchell
matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.imshow.html. You need write plt.imshow(gray, cmap='gray')Winux_RashidLadj

1 Answers

3
votes

You have two options. Keep using pyplot:

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

Or instead using the openCV's default imshow.

cv2.imshow('img', img)
cv2.imshow('new_img', new_img)
cv2.imshow('gray', gray)