【问题标题】:How can I convert a cv::Mat to a gray scale in OpenCv?如何在 OpenCv 中将 cv::Mat 转换为灰度?
【发布时间】:2012-05-07 19:47:42
【问题描述】:

如何将 cv::Mat 转换为灰度?

我正在尝试从 opencv 运行 drawKeyPoints func,但是我收到了 Assertion Filed 错误。我的猜测是它需要在参数中接收灰度图像而不是彩色图像。

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

}

【问题讨论】:

    标签: c++ variables opencv grayscale


    【解决方案1】:

    使用C++ API,函数名略有变化,现在写成:

    #include <opencv2/imgproc/imgproc.hpp>
    
    cv::Mat greyMat, colorMat;
    cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);
    

    主要困难在于该函数在 imgproc 模块中(不在核心中),并且默认情况下 cv::Mat 是蓝绿红(BGR)顺序而不是更多常见的 RGB。

    OpenCV 3

    从 OpenCV 3.0 开始,还有另一个约定。 转换代码嵌入在命名空间cv:: 中,并以COLOR 为前缀。 于是,例子就变成了:

    #include <opencv2/imgproc/imgproc.hpp>
    
    cv::Mat greyMat, colorMat;
    cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);
    

    据我所见,包含的文件路径没有改变(这不是错字)。

    【讨论】:

    • OpenCV 3下,转换类型常量已更改为COLOR_BGR2GRAY
    • 谢谢,我会更新答案。 OpenCV 3 即将推出,它将很有用。
    • @sansuiso 谢谢,您知道如何获得与输入图像具有相同通道的灰度图像吗?目前这种方法,将整个图像转换为 1 通道黑白图像。我应该怎么做才能让我的图像变成黑白而不是 1 通道!
    • 好的,我想我找到了cv::cvtColor(img, greyMat, cv::COLOR_BGR2GRAY); cv::cvtColor(greyMat, greyMat, cv::COLOR_GRAY2BGR);
    【解决方案2】:

    可能对后来者有所帮助。

    #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;
        }
    
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-25
      • 2018-04-16
      • 2011-06-28
      • 2015-11-19
      • 2016-08-16
      • 2021-11-24
      • 2017-06-03
      • 2013-10-21
      相关资源
      最近更新 更多