Difference between plt.imshow and cv2.imshow? - python

Why is there a difference in the output image when calling the same image using plt.imshow & cv2.imshow()?
Here is my code:
import cv2
import numpy as np
from matplotlib import pyplot as plt
src=cv2.imread('fruits1.jpg') # Source image
plt.subplot(211),plt.imshow(src),plt.title('image')
plt.xticks([]),plt.yticks([])
plt.show()
cv2.imshow('image',src)
cv2.waitKey(0)
cv2.destroyWindow()
Here is the image from plt.imshow:
and the second one is the original image:
Is there some modification required with the plt.imshow()?

Because OpenCV stores images in BGR order instead of RGB.
Try plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
See here for an example.

OpenCV - BGR and Matplotlib - RGB
OpenCV:
https://docs.opencv.org/2.4/doc/tutorials/introduction/display_image/display_image.html
Matplotlib:
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imshow.html

you can either use :
plt.imshow(cv2.cvtColor(image,cv2.COLOR_BGR2RGB))
OR
plt.imshow(image[:,:,::-1]) # here we are reversing the channel order

Related

cv2 in Python crashes when I try to open a 4 level CMYK numpy array

import numpy as np
from PIL import Image
import cv2
with Image.open("image.png") as im:
im = im.convert("CMYK")# not a true CMYK conversion here
im.show(title="image")
img = np.array(im)
#cv2.imshow('image', img)
I need to view a CMYK file hopefully using OpenCV and read pixel values in the CMYK space. I tried to load an image, convert it to CMYK(just 4 color levels) and view it using cv2. Note, I have cv2* commented out because it will cause Python to crash and OpenCv will need to be reinstalled. Will OpenCv allow me to view a (x, x, 0:3).uint8 numpy array? If so, throw me a line.
My solution was simple. I forgot the following:
cv2.waitKey(0)
cv2.destroyAllWindows()

cv2.cvtcolor bgr2gray seems get an error image

# the code is as follows, implemented, but the result is possibly wrong, it is not the grayscale i wanted, someone gonna help me with that, it's seems quite simple, but i just don't know what wrong
import cv2
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.image as mpimg
img = cv2.imread('calibration_test.png')
# i want simply convert the rgb image to grayscale and then print it out
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(gray)
print(gray.shape)
# but the outcome is a colorful image
The grayscale conversion was done correctly. The problem is in how you are displaying the image. Try this:
plt.imshow(gray, cmap='gray')
By default imshow adds it's own colour key to single channel images, to make it easier to view. A typical example is thermal images which usually show blue and red, but all the colours are only dependend on one channel.
Hope this helps!

In PIL, why isn't convert('L') turning image grayscale?

For a program I'm writing, I need to convert an RGB image to grayscale and read it as a NumPy array using PIL.
But when I run the following code, it converts the image not to grayscale, but to a strange color distortion a bit like the output of a thermal camera, as presented.
Any idea what the problem might be?
Thank you!
http://www.loadthegame.com/wp-content/uploads/2014/09/thermal-camera.png
from PIL import Image
from numpy import *
from pylab import *
im = array(Image.open('happygoat.jpg').convert("L"))
inverted = Image.fromarray(im)
imshow(inverted)
show()
matplotlib's imshow is aimed at scientific representation of data - not just image data. By default it's configured to use a high constrast color palette.
You can force it to display data using grayscale by passing the following option:
import matplotlib.cm
imshow(inverted, cmap=matplotlib.cm.Greys_r)
Add this code to view/display an image:
from PIL import Image;
from numpy import *
from pylab import *
im = array(Image.open('happygoat.jpg').convert("L"));
inverted = Image.fromarray(im);
inverted

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:
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:
If the matrix does not have any modifications, why the colors in the plot are wrong?
Thanks in advance.
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.
Try:
plt.imshow(cv2.cvtColor(cube, cv2.COLOR_BGR2RGB))
As others have pointed out, the problem is that numpy arrays are in BGR format, but matplotlib expects the arrays to be ordered in a different way.
You are looking for scipy.misc.toimage:
import scipy.misc
rgb = scipy.misc.toimage(cube)
Alternatively, you can use scipy.misc.imshow().
Color image loaded by OpenCV is in BGR mode. However, Matplotlib displays in RGB mode.
So we need to convert the image from BGR to RGB:
plt.imshow(cv2.cvtColor(cube, cv2.COLOR_BGR2RGB))

Scale imread matrix in python

I am looking for a way to rescale the matrix given by reading in a png file using the matplotlib routine imread,
e.g.
from pylab import imread, imshow, gray, mean
from matplotlib.pyplot import show
a = imread('spiral.png')
#generates a RGB image, so do
show()
but actually I want to manually specify the dimension of $a$, say 200x200 entries, so I need some magic command (which I assume exists but cannot be found by myself) to interpolate the matrix.
Thanks for any useful comments : )
Cheers
You could try using the PIL (Image) module instead, together with numpy. Open and resize the image using Image then convert to array using numpy. Then display the image using pylab.
import pylab as pl
import numpy as np
from PIL import Image
path = r'\path\to\image\file.jpg'
img = Image.open(path)
img.resize((200,200))
a = np.asarray(img)
pl.imshow(a)
pl.show()
Hope this helps.

Categories

Resources