Print out the values of a (Mat) matrix in OpenCV C++
See the first answer to Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
Then just loop over all the elements in cout << M.at<double>(0,0);
rather than just 0,0
Or better still with the C++ interface:
cv::Mat M;
cout << "M = " << endl << " " << M << endl << endl;
If you are using opencv3, you can print Mat like python numpy style
:
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;
Output as below, you can see it'e more readable, see here for more information.
But in most case, there is no need to output all the data in Mat, you can output by row range like 0 ~ 2 row:
#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;
}
Output as below:
I think using the matrix.at<type>(x,y)
is not the best way to iterate trough a Mat object!
If I recall correctly matrix.at<type>(x,y)
will iterate from the beginning of the matrix each time you call it(I might be wrong though).
I would suggest using 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;
}