1

I am trying to import a picture of size (540,960) using matplotlib. This step is successfully executed. The result is stored in 'image' object (type ndarray).

# Do relevant imports
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2

# Read in and grayscale the image
image = mpimg.imread(r'C:\Temp\pic24_bw.jpg')
gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)

But when I try to convert the image into another color space (Gray), using cv2.cvtColor(). I face a error:

error: C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:11111:        error: (-215) scn == 3 || scn == 4 in function cv::cvtColor

Please help. Strange thing is this code is running successfully in another citrix environment.

2
  • 1
    Check print(type(image));print(image.dtype, image.shape) Commented Jan 20, 2018 at 12:01
  • are you sure you're reading a 3 channel image? Looks like the image is already grayscale. Commented Jul 18 at 9:21

3 Answers 3

1

This code works for me, load/read your image through cv2 itself and please do recheck your image path as it is the most common mistake, we does.

import numpy as np               
import matplotlib.pyplot as plt
import cv2
%matplotlib inline    
#reading the image 
image = cv2.imread('cat.jpg')
image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
#plotting the image
plt.imshow(image)

Hope this helps you out.

Sign up to request clarification or add additional context in comments.

Comments

0

I tried plt.imshow. The image is successfully loaded. It is shown in a RGB scale.

image = mpimg.imread(r'C:\Temp\pic24_bw.jpg') 
plt.imshow(image,cmap='gray')

1 Comment

maybe plt uses another channel ordering than opencv? Did you try cv2.imread to load the image?
0

This error message appears when the image could not be loaded, or it has an incorrect number of channels (cv2.COLOR_BGR2GRAY needs an image with 3 or 4 channels).

  1. You have to use cv2.imread() instead of mpimg.imread()

  2. If you still have errors, try print(image.shape). Most likely, the image does not have three channels.

You can also try viewing the image with:

cv2.imshow("Test", image)
cv2.waitKey()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.