Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong color reading an image with OpenCV (Python) [duplicate]

Tags:

python

opencv

I'm just starting with OpenCV and Python. I've installed it and started to use with a simply script. I want load an image in color and the same image in B/W. This is the simply code:

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

img1 = cv2.imread("tiger.jpg",3)
img2 = cv2.imread("tiger.jpg",0)

plt.subplot(121),plt.imshow(img1),plt.title('TIGER_COLOR')
plt.subplot(122),plt.imshow(img2),plt.title('TIGER_BW')

plt.show()

Ok, this is the image I'm using with its real color: https://pixabay.com/en/tiger-cub-tiger-cub-big-cat-feline-165189/. The problem is, when I'm show the result of this code, I get this:

enter image description here

As you can see, both images have wrong color. I thought that it would be because I was using an open source graphical driver, but I installed the private one and the problem continues.

How can I fix this? What's the problem? Any ideas? Thanks!

like image 597
Carlos Avatar asked Oct 06 '16 19:10

Carlos


1 Answers

OpenCV does not use RGB, it uses BGR (standing for blue, green, red). You need to swap the order of the red and the blue.

img1 = cv2.imread("tiger.jpg", 3)

b,g,r = cv2.split(img1)           # get b, g, r
rgb_img1 = cv2.merge([r,g,b])     # switch it to r, g, b

plt.subplot(121),plt.imshow(rgb_img1),plt.title('TIGER_COLOR')

Also, your grayscale image is fine, but you are using a colormap for it. Make sure to use

plt.imshow(img2, cmap='gray')
like image 176
Paul Terwilliger Avatar answered Oct 16 '22 02:10

Paul Terwilliger