簡體   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