Search code examples
c++opencvrgbgrayscale

C++ and OpenCV: Issue Converting Image to grayscale


Here is my code. It's pretty simple.

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 image.convertTo(image_gray, CV_RGB2GRAY); line, I get the following error message:

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


Solution

  • The method convertTo does not do color conversion.

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

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