垫子类型转换和访问单个像素时出现问题

Trouble with mat type conversion and accessing individual pixel

本文关键字:问题 像素 单个 类型转换 访问      更新时间:2023-10-16

我在用OpenCV编程时遇到了麻烦。
经过很多时间,我发现,类型转换后,cout <<垫的结果和单个像素值是不同的。

这是代码

#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 <<a 中获得了正确的矩阵,但是在访问单个像素时,我弄得一团糟:|
你可以帮我吗?谢谢!

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

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