Reputation: 1030
I am new to C++ and OpenCV, my current project require some convert from Matrix to grayscale image.
Here i used the function cvtColor, but for some reason it keep crashing cause the error : "OpenCV error: Assertion failed(scn==3 | scn==4) in cv::cvtColor".
Here my source code:
for (int i = 0; i < 2048; i++)
{
for (int j = 0; j < 2048; j++)
{
t[i][j] = abs((L3[i][j] - L_blurred_3[i][j]) / (sqrt(L2_blurred[i][j] - L_blurred_4[i][j])));
}
}
Mat tt(2048, 2048, CV_64F, Scalar(0));
for (int i = 0; i < 2048; i++)
{
for (int j = 0; j < 2048; j++)
{
tt.at<double>(i, j) = t[i][j];
}
}
tt.convertTo(tt, CV_32F);
Mat tgray(2048, 2048, CV_32F, Scalar(0));
cvtColor(tt, tgray, COLOR_BGR2GRAY);
i did make some search on site and google and i have tried many different ways but the result still the same, i know that the problem is my matrix "tt" is a one channel image, so i have 2 main questions:
Upvotes: 1
Views: 1806
Reputation: 20130
according to http://de.mathworks.com/help/images/ref/mat2gray.html matlab mat2gray scales the values in the matrix to fit the range [0..1] (black = 0, white = 1).
so you could just use
cv::normalize(tt, tgray, 0, 1, cv::NORM_MINMAX);
or in general:
cv::normalize(sourceMat, destinationMat, 0, 1, cv::NORM_MINMAX);
Upvotes: 2
Reputation: 2154
As dFionov wrote, all images are matrices. If you want to visualize some float values as grayscale image you need to rescale all values to [0..1] range. For example you may use minMaxLoc
and convertTo
functions as follows:
double minV, maxV;
minMaxLoc(tt, &minV, &maxV);
double alpha = 1. / (maxV - minV);
double beta = -minV * alpha;
Mat gray;
tt.convertTo(gray, CV_32FC1, alpha, beta);
imshow("data", gray);
waitKey();
Ranges for another types are:
unsigned char
unsigned short
float
and double
Upvotes: 2
Reputation: 129
All images is matrices. You can see what you get in cv::Mat
with imshow("Image", tt)
.
And in line:
cvtColor(tt, tgray, COLOR_BGR2GRAY);
You trying to convert matrix with 3 or 4 plains to matrix with 1 plain. Conversion type controls by COLOR_BGR2GRAY
constant. Information about cvtColor()
function you can find in OpenCV documentation
In this case you don't need to convert your tt matrix - it is already grayscale image.
Upvotes: 1