# CV_64F ConvertTo CV_8U Problem with cast

Hi everyone, I try to cast a CV_64F Mat into a CV_8U Mat for thresholding (See code below). Unfortunately this doesn't work the way i want it to. If you uncomment the cout-command you will see that the whole mat contains ones. What am i doing wrong? Thank you for your help!

Mat testMat = Mat(10, 10, CV_64F);
double above = 0.9111;
double below = 0.6665;
double minDbl = 0.9;
// Fill Mat:
for (int rows=0; rows<testMat.rows; rows++)
{
for (int cols=0; cols<testMat.cols; cols++)
{
if (rows < 5)
testMat.at<double>(rows, cols) = above;
else
testMat.at<double>(rows, cols) = below;
}
}
//cout << testMat;

Mat convertedMat;
testMat.convertTo(convertedMat, CV_8U);

//cout << convertedMat;

//What i actually want:
cv::threshold(convertedMat, convertedMat, minDbl, 1., CV_THRESH_TOZERO);
//cout << convertedMat;

edit retag close merge delete

2

you can also avoid both the conversion and the threshold function, and do a direct comparison:

Mat mask = testMat>0.9;
// mask /= 255; // if you want it in 0..1

2

Sort by » oldest newest most voted

Yes 0.911 becomes 1 and 0.66 becomes 1 too

You should use :

 testMat.convertTo(convertedMat, CV_8U,255,0);

cv::threshold(convertedMat, convertedMat, 255*minDbl, 1., CV_THRESH_TOZERO);


Loops now use opencv function instead of for

testMat.rowRange(Range(0,5))= above;
testMat.rowRange(5,testMat.rows)= below;

more

Thank you that was exactly what i was looking for! For my understandings: the scaling factor 255 means the double was multiplied by that and casted afterwards, is that right?

Also thank you for your second comment: I didn't know the range operator. But for single pixel acess at is the right way?

"the scaling factor 255 means the double was multiplied by that and casted afterwards" I think so but you have to dig in code if you want to be sure. In my configuration convertto called

CV_INSTRUMENT_FUN_IPP(::ipp::iwiScale, &iwSrc, &iwDst, alpha, beta, mode);

Of course for single pixel called at but code for colrange or rowRange is optimized via ipp

Official site

GitHub

Wiki

Documentation