-3

How can I solve this error ?

import matplotlib, cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('C:/Users/xxx/Desktop/image.jpg') 
img = np.array(img, dtype=np.uint8)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_GRAY2RGB))

error: OpenCV(4.0.0) c:\projects\opencv-python\opencv\modules\imgproc\src\color.hpp:259: error: (-2:Unspecified error) in function '__cdecl cv::CvtHelper,struct cv::Set<3,4,-1>,struct cv::Set<0,2,5>,2>::CvtHelper(const class cv::_InputArray &,const class cv::_OutputArray &,int)'

Invalid number of channels in input image: 'VScn::contains(scn)' where 'scn' is 3

gameon67
  • 3,981
  • 5
  • 35
  • 61
Mayar
  • 11
  • 1
  • 2

2 Answers2

1
img = cv2.imread(filename[, flags])

returns a 3-channel color image when flag>0

returns a gray image when flag=0

returns a image as the loaded file originally is.

You got the error because you didn't assign it to return a gray image. And the channel number didn't match.

Use img = cv2.imread(filename, 0) to make sure img is a 1-channel image.

0

The image you load with imread contains three channels in BGR-format. However, cv2.cvtColor expects an image with only one channel, because you passed the parameter cv2.COLOR_GRAY2RGB (grayscale images only have a single channel)

If you need RGB consider using:

cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

Simon
  • 9,255
  • 4
  • 37
  • 54