简体   繁体   中英

OpenCV C++: Conversion from CV_32F to CV8U using converTo is giving unexpected values

cv::Mat x(2,2,CV_32F);
x.at<float>(0,0)=0.7;
x.at<float>(0,1) = 0.8;
x.at<float>(1,0) = 0.72;
x.at<float>(1,1) = 0.68;
x.convertTo( x, CV_8U, 255, 0  );
std::cout << x.at<int>(0,0)  << std::endl;
std::cout << x.at<int>(0,1)  << std::endl;
std::cout << x.at<float>(1,0)  << std::endl; // I deliberately put <float> just to see what happens
std::cout << x.at<int>(1,1)  << std::endl;

The output is:

-1380397902 1 1.54154e-40 0

I was expecting an output like:

178 204 184 173

What am I doing wrong?

if your Mat is CV_8U now, you will have to access it as

x.at<uchar>(1,1)

the next problem will be printing out the number correctly, cout, seeing a char , will try to print a letter, so you will have to cast it to int:

std::cout << int(x.at<uchar>(0,0))  << std::endl;

then, if your mat is 2x2, you can't access an element at 2,2, this is out of bounds, and will lead to UB. !

(in c++, we index from 0..n-1, right ?)

so, here, the corrected example:

cv::Mat x(2,2,CV_32F);
x.at<float>(0,0)=0.7;
x.at<float>(1,0) = 0.8;
x.at<float>(0,1) = 0.72;
x.at<float>(1,1) = 0.68;
Mat y;

x.convertTo( y, CV_8U, 255, 0  );
cout << int(y.at<uchar>(0,0))  << std::endl;
cout << int(y.at<uchar>(1,0))  << std::endl;
cout << int(y.at<uchar>(0,1))  << std::endl;
cout << int(y.at<uchar>(1,1))  << std::endl;

cerr << x << endl;
cerr << y << endl;

178
204
184
173
[0.69999999, 0.72000003;
  0.80000001, 0.68000001]
[178, 184;
  204, 173]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM