C++ 如何在 OpenCv 中将 cv::Mat 转换为灰度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10344246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert a cv::Mat to a gray scale in OpenCv?
提问by user1319603
How can I convert a cv::Mat to a gray scale?
如何将 cv::Mat 转换为灰度?
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.
我正在尝试从 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);
}
}
回答by sansuiso
Using the C++ API, the function name has slightly changed and it writes now:
使用 C++ API,函数名称略有变化,现在写成:
#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 imgprocmodule (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.
主要困难在于该函数位于imgproc模块中(不在核心中),并且默认情况下 cv::Mat 处于蓝绿红 (BGR) 顺序而不是更常见的 RGB。
OpenCV 3
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:
从 OpenCV 3.0 开始,还有另一个约定。转换代码嵌入在命名空间中cv::
,并以COLOR
. 因此,示例变为:
#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).
据我所知,包含的文件路径没有改变(这不是错字)。
回答by Chanaka Fernando
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;
}
}
}