2011-11-01 122 views
46

我想要使用cout將OpenCV中的矩陣值轉儲到控制檯。我很快就瞭解到,我不明白OpenvCV的類型系統和C++模板能夠完成這個簡單的任務。打印OpenCV中的(矩陣)矩陣的值C++

請讀者發佈(或指向我)一個打印Mat的小函數或代碼片段嗎?

問候, 亞倫

PS:代碼,使用較新的C++墊接口,而不是舊的接口CvMat中是優先。

回答

68

見第一答案Accesing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
然後,只需遍歷所有元素cout << M.at<double>(0,0);,而不僅僅是0,0

或者與new C++ interface(感謝SSteve

cv::Mat M; 

cout << "M = "<< endl << " " << M << endl << endl; 
+1

另請參見[教程的這一部分(http://opencv.itseez.com/doc/tutorials/core/mat%20-%20the%20basic%20image%20container /mat%20-%20the%20basic%20image%20container.html#print-out-formatting) – SSteve

+1

輝煌。我應該首先推出一個墊來看看是否有人實施了<<。多一點實驗和信任會爲我付出代價。 – ahoffer

+0

我剛剛問過[關於此問題](http://stackoverflow.com/questions/10011797/opencv-2-1-where-is-ostream-operator-for-cvmat)。 ostream運算符是否可以在2.1中找到,這些東西在哪裏記錄下來? – juanchopanza

3
#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; 
} 
更好
3

我認爲使用matrix.at<type>(x,y)不是迭代通過Mat對象的最佳方法! 如果我記得正確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; 
}