问题
I have to process a matrix and then scale it as a gray scale image. In matlab I could achieve this using mat2gray function. How can I do the same in opencv?
for(int i=0;i<c4.rows-1;i++)
{
for(int j=0;j<c4.cols-1;j++)
{
value=100*sin(2*pi*j*18.0/imgCols);
c5.at<Vec2d>(i,j)=value;
}
}
回答1:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);
回答2:
If you have already single channel matrices and want to scale their values between 0 and 1 (for displaying), try this one:
cv::Mat mat2gray(cv::Mat inMat)
{
//idea: to be scaled between 0 and 1, compute for each value: val := (val - minVal)/(maxVal-minVal)
if(inMat.channels() != 1) std::cout << "mat2gray only works for single channel floating point matrices" << std::endl;
// here we assume floating point matrices (single/double precision both ok)
double minVal, maxVal;
cv::minMaxLoc(inMat, &minVal, &maxVal);
cv::Mat scaledMat = inMat.clone();
scaledMat = scaledMat - cv::Mat(inMat.size(), inMat.type(), cv::Scalar(minVal));
scaledMat = ((1.0)/(maxVal-minVal))*scaledMat;
return scaledMat;
}
来源:https://stackoverflow.com/questions/27483013/scaling-a-matrix-in-opencv