Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = [] images.append(img) images.append(bw_img)  titles = ['Original Image','BW Image']  for i in xrange(len(images)):     plt.subplot(1,2,i+1),plt.imshow(images[i],'gray')     plt.title(titles[i])     plt.xticks([]),plt.yticks([])  plt.show() 

Here is the original image: enter image description here

And here is the plotted image: enter image description here

like image 301
bholagabbar Avatar asked Sep 04 '16 11:09

bholagabbar


People also ask

Is OpenCV BGR or RGB?

OpenCV uses BGR image format. So, when we read an image using cv2. imread() it interprets in BGR format by default. We can use cvtColor() method to convert a BGR image to RGB and vice-versa.

Can OpenCV detect colors?

OpenCV has some built-in functions to perform Color detection and Segmentation operations. So what are Color Detection and Segmentation Techniques in Image Processing? Color detection is a technique of detecting any color in a given range of HSV (hue saturation value) color space.

How do I convert BGR to RGB in cv2?

Convert BGR and RGB with OpenCV function cvtColor() When code is cv2. COLOR_BGR2RGB , BGR is converted to RGB.


2 Answers

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.

like image 195
TobyD Avatar answered Oct 06 '22 21:10

TobyD


As an alternative to the previous answer, you can use (slightly faster)

img = cv2.imread('lena_caption.png')[...,::-1]

%timeit [cv2.cvtColor(cv2.imread(f), cv2.COLOR_BGR2RGB) for f in files]
231 ms ± 3.08 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit [cv2.imread(f)[...,::-1] for f in files]
220 ms ± 1.81 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

like image 34
okk Avatar answered Oct 06 '22 21:10

okk