问题源:https://github.com/gzr2017/ImageProcessing100Wen
问题描述:
这里提供一种opencv455中cvtColor函数的方法:
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat img=imread("C:/Users/79490/Desktop/ImageProcessing100Wen-master/ImageProcessing100Wen-master/Question_01_10/imori.jpg",IMREAD_COLOR);
Mat img_gray;
cvtColor(img,img_gray,COLOR_BGR2GRAY);
imshow("img_gray",img_gray);
waitKey(0);
return 0;
}
官网参考答案,注意单通道Mat的赋值格式,是uchar,不是Vec3b;且,将原图像bgr值赋给灰度图时,得强制转换成(float):
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
Mat gray(Mat img){
int rows(img.rows),cols(img.cols);
Mat img_gray = Mat::zeros(rows,cols,CV_8UC1);
for(int i(0);i<rows;i++){
for(int j(0);j<cols;j++){
img_gray.at<uchar>(i,j)=0.2126*(float)img.at<Vec3b>(i,j)[2]+0.7152*(float)img.at<Vec3b>(i,j)[1]+0.0722*(float)img.at<Vec3b>(i,j)[0];
}
}
return img_gray;
}
int main()
{
Mat img=imread("C:/Users/79490/Desktop/ImageProcessing100Wen-master/ImageProcessing100Wen-master/Question_01_10/imori.jpg",IMREAD_COLOR);
Mat img_gray=gray(img);
imshow("img_gray",img_gray);
waitKey(0);
return 0;
}