Shankar S
Shankar S

Reputation: 193

cannot read in image in colour in opencv python

I have just started to use Opencv using python in windows(PyCharm IDE). I tried to read a color image. But it got displayed in Grayscale. So I tried to convert it as below:

import cv2
img = cv2.imread('C:\Ai.jpg', 0)
b,g,r = cv2.split(img)
rgb = cv2.merge([r,g,b])
cv2.imshow('image', img)
cv2.imshow('rgb image',rgb)
cv2.waitKey(0)
cv2.destroyAllWindows()

But i am getting an error:

"b, g, r = cv2.split(img) ValueError: need more than 1 value to unpack"

Can you guys please help me out? Thanks in advance.

Upvotes: 2

Views: 11225

Answers (2)

Yogesh Awdhut Gadade
Yogesh Awdhut Gadade

Reputation: 2708

Try this solution

Read and convert image into RGB format:

If you have a color image and reading it using OpenCV. First, convert it in RGB colour format

image = cv2.imread(C:\Ai.jpg')                 #cv2 reading image in BGR
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) #convert it into RGB format

To display it we can use cv2.imshow, matplotlib or PIL as follows

import matplotlib.pyplot as plt
%matplotlib inline
from PIL import Image

Now print using matplotlib:

plt.imshow(image)

print using PIL

Image.fromarray(image)

Upvotes: 0

ZdaR
ZdaR

Reputation: 22954

There is a problem in the second line of your code img = cv2.imread('C:\Ai.jpg', 0), as per the documentation, 0 value corresponds to cv2.IMREAD_GRAYSCALE, This is the reason why you are getting a grayscale image. You may want to change it to 1 if you want to load it in RGB color space or -1 if you want to include any other channel like alpha channel which is encoded along with the image.

And b,g,r = cv2.split(img) was raising an error because img at that point of time is a grayscale image which had only one channel, and it is impossible to split a 1 channel image to 3 respective channels.

Your final snippet may look like this:

import cv2
# Reading the image in RGB mode
img = cv2.imread('C:\Ai.jpg', 1)

# No need of following lines:
# b,g,r = cv2.split(img)
# rgb = cv2.merge([r,g,b])
# cv2.imshow('rgb image',rgb)

# Displaying the image
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Upvotes: 1

Related Questions