-1

I am trying to convert an image from RGB to grayscale. My image looks like this after reading

img = cv2.imread('sample.png')
plt.imshow(img)

enter image description here

I tried converting this to grayscale using cv2 function and the image looks as below after conversion:

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(gray)

enter image description here

As you can see image is not converted to grayscale properly. What could be the reason? Am I missing something here?

iamkk
  • 135
  • 1
  • 16
  • Can you please try `cv2.COLOR_RGB2GRAY` instead of `cv2.COLOR_BGR2GRAY`. Maybe the order of the colors is not `BGR`. – mosc9575 Mar 15 '21 at 09:22
  • @mosc9575 I have already tried that, but no luck. I end up with the same image. – iamkk Mar 15 '21 at 09:23
  • Duplicate: [opencv convert image to grayscale, and display using matplotlib gives strange color](https://stackoverflow.com/questions/52333972/opencv-convert-image-to-grayscale-and-display-using-matplotlib-gives-strange-co) – HansHirse Mar 15 '21 at 09:34

1 Answers1

1

The default option for cmap in plt.imshow is viridis. Use plt.imshow(gray, cmap='gray') for grayscale images. If you save the image using cv2.imwrite you can see the image has been converted to grayscale.

DragonsCanDance
  • 441
  • 4
  • 14
  • when I save an image with `cv2.imwrite`, and read again using `cv2.imread` I see that the image has three channels. How can I store the gray images with 1 channel? – iamkk Mar 15 '21 at 12:37
  • 1
    `cv2.imread(path, flag)` , set flag to `cv2.IMREAD_GRAYSCALE` – DragonsCanDance Mar 15 '21 at 12:45