6

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!

Carlos
  • 889
  • 3
  • 12
  • 34
  • 1
    OpenCV uses BGR, not RGB. So simply swap the B and R channels before showing the image `rgb = img1[(2,1,0),:,:]) plt.imshow(rgb)`, or use [cvtColor](http://www.pyimagesearch.com/2014/11/03/display-matplotlib-rgb-image/). The grayscale image is ok, you're just using a colormap. Use `plt.imshow(img2, cmap='gray')` – Miki Oct 06 '16 at 19:16

1 Answers1

17

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')
Paul Terwilliger
  • 1,596
  • 1
  • 20
  • 45
  • 2
    Thanks! All the problem was the mistake between RGB and BGR and the color map. Why OpenCV decided to use a system (BGR) as non-universal as RGB? – Carlos Oct 07 '16 at 14:12