How to convert BGR to RGB in OpenCV Python?

OpenCV reads the image in BGR mode, whereas Matplotlib needs the image to be in RGB mode. That is why you might face a situation in which you need to display an image using Matplotlib. In that case, you have to convert the image to RGB mode and for this use cv2.cvtColor() function and pass cv2.COLOR_BGR2RGB flag to it.

import cv2

img = cv2.imread('/home/mohit/cardiff.jpg')
if img is None:
  print('Image is not present.')
else:
  img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  cv2.imshow(img)
  cv2.destroyAllWindows()
  cv2.waitKey(0)

Output

convert BGR to RGB in OpenCV Python

Original Image

OpenCV read image