bholagabbar bholagabbar - 1 year ago 153
Python Question

OpenCV giving wrong color to colored images on loading

I'm loading in a color image in Python OpenCV and plotting the same. However, the image I get has it's colors all mixed up.

Here is the code:

import cv2
import numpy as np
from numpy import array, arange, uint8
from matplotlib import pyplot as plt

img = cv2.imread('lena_caption.png', cv2.IMREAD_COLOR)
bw_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

images = []

titles = ['Original Image','BW Image']

for i in xrange(len(images)):

Here is the original image:
enter image description here

And here is the plotted image:
enter image description here

Answer Source

OpenCV uses BGR as its default colour order for images, matplotlib uses RGB. When you display an image loaded with OpenCv in matplotlib the channels will be back to front.

The easiest way of fixing this is to use OpenCV to explicitly convert it back to RGB, much like you do when creating the greyscale image.

    RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

And then use that in your plot.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download