Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib imshow distorting colors [duplicate]

I have tried to use the imshow function from matplotlib.pyplot and it works perfectly to show grayscale images. When I tried to represent rgb images, it changes the colors, showing a more blue-ish color.

See an example:

import cv2
import matplotlib.pyplot as plt
lena=cv2.imread("lena.jpg")
plt.imshow(lena)
plt.show()

The resulting image is something like this

While the original image is this

If it is something related to the colormap, there is any way to make it work with rgb images?

like image 860
dberga Avatar asked May 31 '18 18:05

dberga


2 Answers

This worked for me:

plt.imshow(lena[:,:,::-1]) # RGB-> BGR

Same idea but nicer and more robust approach is to use "ellipsis" proposed by @rayryeng:

plt.imshow(lena[...,::-1])
like image 84
AGN Gazer Avatar answered Sep 26 '22 09:09

AGN Gazer


OpenCV represents the images in BGR as opposed to the RGB we expect. Since it is in the reverse order, you tend to see the blue color in images. Try using the following line (below comment in code) for converting from BGR to RGB:

import cv2
import matplotlib.pyplot as plt
lena=cv2.imread("lena.jpg")
#plt.imshow(lena)
#plt.axis("off")
#Converts from BGR to RGB
plt.imshow(cv2.cvtColor(lena, cv2.COLOR_BGR2RGB))
plt.show()
like image 37
pragmaticprog Avatar answered Sep 22 '22 09:09

pragmaticprog