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:
And here is the plotted image:
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.
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.
Convert BGR and RGB with OpenCV function cvtColor() When code is cv2. COLOR_BGR2RGB , BGR is converted to RGB.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With