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;
输出结果为:
-1380397902 1 1.54154e-40 0
我期待输出如下:
178 204 184 173
我做错了什么?
答案 0 :(得分:3)
如果您的Mat现在是CV_8U,则必须以
的形式访问它x.at<uchar>(1,1)
下一个问题是正确打印出数字,cout,看到一个字母,会尝试打印一个字母,所以你必须把它转换为int:
std::cout << int(x.at<uchar>(0,0)) << std::endl;
然后,如果你的垫子是2x2,你不能访问2,2的元素,这是超出范围,并将导致UB。 !
(在c ++中,我们从0..n-1索引,对吗?)
所以,这里是更正后的例子:
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]