Jason
Jason

Reputation: 13956

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

Upvotes: 3

Views: 8899

Answers (4)

Vimukthi Gunasekara
Vimukthi Gunasekara

Reputation: 41

image.convertTo(image_gray, CV_RGB2GRAY); This's wrong.Correct one is,

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

Try this.

Upvotes: 0

roadrunner66
roadrunner66

Reputation: 7941

If you need to acquire video (e.g. from a webcam) in Grayscale, you can also set the saturation of the video feed to zero. (Ex. in Python syntax)

 capture = cv.CaptureFromCAM(camera_index) 

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

Upvotes: 0

sgarizvi
sgarizvi

Reputation: 16796

The function cv::Mat::convertTo is not for color conversion. It is for type conversion. The destination image should have same size and number of channels as the source image.

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

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

Upvotes: 0

Ove
Ove

Reputation: 6317

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);

Upvotes: 7

Related Questions