C ++ and OpenCV: the problem of converting an image to grayscale

Here is my code. It's pretty straightforward.

Mat image  = imread("filename.png");

imshow("image", image);
waitKey();

//Image looks great.

Mat image_gray;
image.convertTo(image_gray, CV_RGB2GRAY);

imshow("image", image_gray);
waitKey();

      

But when I call the line image.convertTo(image_gray, CV_RGB2GRAY);

, I get the following error:

OpenCV Error: Assertion failed (func != 0) in unknown function, file ..\..\..\sr
c\opencv\modules\core\src\convert.cpp, line 1020

      

Using OpenCV 2.4.3

+3


source to share


4 answers


The method convertTo

does not perform color conversions.

If you want to convert from BGR to GRAY, you can use the cvtColor function :



Mat image_gray;
cvtColor(image, image_gray, CV_BGR2GRAY);

      

+5


source


The function is cv::Mat::convertTo

not intended for color conversion. This is for type conversion. The destination image must have the same size and number of channels as the original image.

To convert from RGB to gray, use the function cv::cvtColor

.



cv::cvtColor(image,image_gray,CV_RGB2GRAY);

      

0


source


If you need to receive video (for example, from a webcam) in grayscale, you can also set the saturation of the video feed to zero. (Example in Python syntax)

 capture = cv.CaptureFromCAM(camera_index) 

      

...

cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_SATURATION,0)

0


source


image.convertTo (image_gray, CV_RGB2GRAY); This is not true. Correct option:

 Mat gray_image;
 cvtColor(image, gray_image, CV_BGR2GRAY);

      

Try it.

0


source







All Articles