垫类型转换和访问单个像素的麻烦

时间:2013-11-11 15:04:51

标签: c++ opencv mat

使用OpenCV进行编程时遇到了麻烦 经过很长一段时间后,我发现cout的结果<< mat和单个像素值在类型转换后不同。

这是代码

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace std;
using namespace cv;

int main() {
Mat a = (Mat_<int>(3, 3) << 1, 2, 3, 4, 5, 6, 7, 8, 9);
cout << "Initial mat type: " << a.type() << endl;
cout << "Pos(1, 1): " << a.at<int>(1, 1) << endl;

a.convertTo(a, CV_8U);
cout << "CV_8U converted mat type: " << a.type() << endl;
cout << "Mat content: \n" << a << endl;
cout << "Pos(1, 1): " << a.at<int>(1, 1) << endl;

return 0;
}

结果在这里:

Initial mat type: 4 // CV_32S 
Pos(1, 1): 5
CV_8U converted mat type: 0 // CV_8U
Mat content: 
[1, 2, 3;
  4, 5, 6;
  7, 8, 9]
Pos(1, 1): -1254749944

这意味着,在从CV_32S转换为CV_8U之后,我从cout&lt;&lt;获得了正确的矩阵。 a,但是当访问单个像素时,我弄得一团糟:|
你能帮助我吗?谢谢!

1 个答案:

答案 0 :(得分:2)

由于您已将值转换为其他类型,因此需要使用其他类型访问它们:

cout << "Pos(1, 1): " << static_cast<int>(a.at<uchar>(1, 1)) << endl;