How can I convert a cv::Mat to a gray scale?
I am trying to run drawKeyPoints func from opencv, however I have been getting an Assertion Filed error. My guess is that it needs to receive a gray scale image rather than a color image in the parameter.
void SurfDetector(cv::Mat img){ vector<cv::KeyPoint> keypoints; cv::Mat featureImage; cv::drawKeypoints(img, keypoints, featureImage, cv::Scalar(255,255,255) ,cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS); cv::namedWindow("Picture"); cv::imshow("Picture", featureImage);
}
Step 1: Import OpenCV. Step 2: Read the original image using imread(). Step 3: Convert to grayscale using cv2. cvtcolor() function.
Right-click the picture that you want to change, and then click Format Picture on the shortcut menu. Click the Picture tab. Under Image control, in the Color list, click Grayscale or Black and White.
To convert an image to its GrayScale in C++ with OpenCV Then we read the image. We use function cvtcolor() to convert the image to it's Grayscale equivalent. This function does require changes to the Red, Green, Blue variants of color. Imshow() function is used to show the converted image and the previous one as well.
If you need a grayscale image, use: C++ Mat img = imread(filename, IMREAD_GRAYSCALE);
Using the C++ API, the function name has slightly changed and it writes now:
#include <opencv2/imgproc/imgproc.hpp> cv::Mat greyMat, colorMat; cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);
The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.
OpenCV 3
Starting with OpenCV 3.0, there is yet another convention. Conversion codes are embedded in the namespace cv::
and are prefixed with COLOR
. So, the example becomes then:
#include <opencv2/imgproc/imgproc.hpp> cv::Mat greyMat, colorMat; cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);
As far as I have seen, the included file path hasn't changed (this is not a typo).
May be helpful for late comers.
#include "stdafx.h" #include "cv.h" #include "highgui.h" using namespace cv; using namespace std; int main(int argc, char *argv[]) { if (argc != 2) { cout << "Usage: display_Image ImageToLoadandDisplay" << endl; return -1; }else{ Mat image; Mat grayImage; image = imread(argv[1], IMREAD_COLOR); if (!image.data) { cout << "Could not open the image file" << endl; return -1; } else { int height = image.rows; int width = image.cols; cvtColor(image, grayImage, CV_BGR2GRAY); namedWindow("Display window", WINDOW_AUTOSIZE); imshow("Display window", image); namedWindow("Gray Image", WINDOW_AUTOSIZE); imshow("Gray Image", grayImage); cvWaitKey(0); image.release(); grayImage.release(); return 0; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With