31

I am trying to display an RGB image using matplotlib. This is the code:

# import libraries
import numpy as np
import cv2
from matplotlib import pyplot as plt

# use opencv to load the image
image = cv2.imread("path/to/file/image.jpg", 1)

# convert it to numpy array
pixels = np.array(image)

And then, when I try to visualize the image with:

plt.imshow(pixels)
plt.show()

It returns a picture that is all blue. I don't understand why, since the image is a normal colored image. I tried with multiple images, and the problem persists. Moreover, with my laptop at work I didn't get any problem.

Leevo
  • 1,683
  • 2
  • 17
  • 34

2 Answers2

35

You are facing this issue since you are reading the image with opencv and opencv reads and displays an image as BGR format instead of RGB color format. Whereas matplotlib uses RGB color format to display image. Try using:

image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

pixels = np.array(image)

plt.imshow(pixels)
plt.show()
Apoorv Mishra
  • 1,489
  • 1
  • 8
  • 12
29

you can directly use this line to convert the BGR image to RGB:

image = cv2.imread("path/to/file/image.jpg")[:,:,::-1]
noiaverbale
  • 1,550
  • 13
  • 27
Akhil prasannan
  • 395
  • 4
  • 11