OpenCV giving wrong color to colored images on loading OpenCV giving wrong color to colored images on loading python python

OpenCV giving wrong color to colored images on loading


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)


Simple one-line solution

np.flip(img, axis=-1) 

This can convert both ways. From RGB to BGR, and from BGR to RGB.