Extracting a region from an image using slicing in Python, OpenCV

Best way to do this is to use :-
img2 = cv2.cvtColor(img , cv2.COLOR_BGR2RGB)

This will convert the BGR 'img' array to RGB 'img2' array. Now you can use img2 array for imshow() function of matplotlib.

Refer Link:- cvtColor


2 more options not mentioned yet:

img[..., ::-1] # same as the mentioned img[:, :, ::-1] but slightly shorter

and the versatile

cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

There is a slight difference in pixel ordering in OpenCV and Matplotlib.

OpenCV follows BGR order, while matplotlib likely follows RGB order.

So when you display an image loaded in OpenCV using pylab functions, you may need to convert it into RGB mode. ( I am not sure if any easy method is there). Below method demonstrate it:

import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('messi4.jpg')
b,g,r = cv2.split(img)
img2 = cv2.merge([r,g,b])
plt.subplot(121);plt.imshow(img) # expects distorted color
plt.subplot(122);plt.imshow(img2) # expect true color
plt.show()

cv2.imshow('bgr image',img) # expects true color
cv2.imshow('rgb image',img2) # expects distorted color
cv2.waitKey(0)
cv2.destroyAllWindows()

NB : Please check @Amro 's comment below for better method of conversion between BGR and RGB. img2 = img[:,:,::-1] . Very simple.

Run this code and see the difference in result yourself. Below is what I got :

Using Matplotlib :

enter image description here

Using OpenCV :

enter image description here