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.

Tanay
  • 167
  • 1
  • 2
  • 7

3 Answers3

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.

ambar mishra
  • 64
  • 1
  • 5
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')
Tanay
  • 167
  • 1
  • 2
  • 7
  • 1
    maybe plt uses another channel ordering than opencv? Did you try cv2.imread to load the image? – Micka Jan 20 '18 at 12:23
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()
Totoro
  • 3,398
  • 1
  • 24
  • 39