繁体   English   中英

在 OpenCV C++ 中打印出(Mat)矩阵的值

[英]Print out the values of a (Mat) matrix in OpenCV C++

我想使用 cout 将 OpenCV 中的矩阵值转储到控制台。 我很快了解到我对 OpenvCV 的类型系统和 C++ 模板的了解不足以完成这个简单的任务。

请读者发布(或指向我)一个打印 Mat 的小函数或代码片段吗?

问候,亚伦

PS:使用较新的 C++ Mat 接口而不是较旧的 CvMat 接口的代码是优先的。

请参阅在 OpenCV C++ 中访问“Mat”对象(不是 CvMat 对象)中的矩阵元素的第一个答案
然后循环遍历cout << M.at<double>(0,0);所有元素cout << M.at<double>(0,0); 而不仅仅是 0,0

或者使用 C++ 接口更好:

cv::Mat M;
cout << "M = " << endl << " "  << M << endl << endl;

如果您使用的是 opencv3,则可以像python numpy style一样打印 Mat:

Mat xTrainData = (Mat_<float>(5,2) << 1, 1, 1, 1, 2, 2, 2, 2, 2, 2);

cout << "xTrainData (python)  = " << endl << format(xTrainData, Formatter::FMT_PYTHON) << endl << endl;

输出如下,您可以看到它更具可读性,请参阅此处了解更多信息。

在此处输入图片说明

但在大多数情况下,不需要输出 Mat 中的所有数据,您可以按行范围输出,如 0 ~ 2 行:

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <iomanip>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    //row: 6, column: 3,unsigned one channel
    Mat image1(6, 3, CV_8UC1, 5);

    // output row: 0 ~ 2
    cout << "image1 row: 0~2 = "<< endl << " "  << image1.rowRange(0, 2) << endl << endl;

    //row: 8, column: 2,unsigned three channel
    Mat image2(8, 2, CV_8UC3, Scalar(1, 2, 3));

    // output row: 0 ~ 2
    cout << "image2 row: 0~2 = "<< endl << " "  << image2.rowRange(0, 2) << endl << endl;

    return 0;
}

输出如下:

在此处输入图片说明

我认为使用matrix.at<type>(x,y)不是遍历 Mat 对象的最佳方法! 如果我没matrix.at<type>(x,y)话, matrix.at<type>(x,y)每次调用时都会从矩阵的开头开始迭代(不过我可能是错的)。 我建议使用cv::MatIterator_

cv::Mat someMat(1, 4, CV_64F, &someData);;
cv::MatIterator_<double> _it = someMat.begin<double>();
for(;_it!=someMat.end<double>(); _it++){
    std::cout << *_it << std::endl;
}
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <iomanip>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    double data[4] = {-0.0000000077898273846583732, -0.03749374753019832, -0.0374787251930463, -0.000000000077893623846343843};
    Mat src = Mat(1, 4, CV_64F, &data);
    for(int i=0; i<4; i++)
        cout << setprecision(3) << src.at<double>(0,i) << endl;

    return 0;
}

除了上述出色的答案之外,您当然可以通过 FileStorage 打印出 Mat 值,如果您的案例考虑使用文件

// create our writer 
FileStorage fs("test.yml", FileStorage::WRITE);
fs << "Result" << Mat::eye(5,5, CV_64F);
// release the file 
fs.release();

// read file
FileStorage fs2("test.yml", FileStorage::READ);

Mat r2;
fs2["Result"] >> r2;
std::cout << r2 << std::endl;

fs2.release();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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