How can I convert a cv::Mat to a gray scale in OpenCv?

前端 未结 2 1225
逝去的感伤
逝去的感伤 2020-12-24 11:11

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 tha

相关标签:
2条回答
  • 2020-12-24 11:21

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

    0 讨论(0)
  • 2020-12-24 11:32

    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;
        }
    
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题