Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert colors when plotting a PNG file using matplotlib

I'm trying to display a PNG file using matplotlib and of course, python. For this test, I've generated the following image: Original File

Now, I load and transform the image into a multidimensional numpy matrix:

import numpy as np
import cv2
from matplotlib import pyplot as plt

cube = cv2.imread('Graphics/Display.png')
plt.imshow(cube)
plt.ion()

When I try to plot that image in matplotlib, the colors are inverted:Plot

If the matrix does not have any modifications, why the colors in the plot are wrong?

Thanks in advance.

like image 735
Edgar Andrés Margffoy Tuay Avatar asked Jan 17 '13 20:01

Edgar Andrés Margffoy Tuay


People also ask

How do you invert colors on a PNG?

Go the Advanced tab and select Add Effect/Annotation->Color processing->Brightness-Contrast. Check the box Invert. Click Start! and your PNG photos will soon be inverted.

How do you reverse a color map in Python?

We can reverse the colormap of the plot with the help of two methods: By using the reversed() function to reverse the colormap. By using “_r” at the end of colormap name.

How do you negate colors in python?

invert() for Negating color.


2 Answers

It appears that you may somehow have RGB switched with BGR. Notice that your greens are retained but all the blues turned to red. If cube has shape (M,N,3), try swapping cube[:,:,0] with cube[:,:,2]. You can do that with numpy like so:

rgb = numpy.fliplr(cube.reshape(-1,3)).reshape(cube.shape)

From the OpenCV documentation:

Note: In the case of color images, the decoded images will have the channels stored in B G R order.

like image 200
bogatron Avatar answered Oct 09 '22 18:10

bogatron


Try:

plt.imshow(cv2.cvtColor(cube, cv2.COLOR_BGR2RGB))
like image 44
Alex Rothberg Avatar answered Oct 09 '22 18:10

Alex Rothberg