Kuo
Kuo

Reputation: 29

How to store and read integer matrix by OpenCV?

I want to build an openCV matrix. The following is my code.

int data[9]={0,1,0,0,-1,0,0,0,0};
cv::Mat m(3, 3, CV_8SC1,data);
cout<<(int)m.at<char>(0,1)<<endl;
cout<<(int)m.at<schar>(0,1)<<endl;

There is no result shown in my monitor. But, if I change my code to the following.

float data[9]={0,1,0,0,-1,0,0,0,0};
cv::Mat m(3, 3, CV_32FC1,data);
cout<<m.at<float>(0,1)<<endl;

The "1" will be shown. However, if I use type "float" instead of "int", I need to spend redundant memory to store number "1", "0" or "-1". Is there any who know how to save integer with openCV? Thank you.


After searching more website, I found a solution as following .

cv::Mat C = (cv::Mat_<int>(3,3) << 0, 1, 0, 0, -1, 0, 0, 0, 0);
cout << "C = " << endl << " " << C.at<int>(0,1)<<endl;

Upvotes: 0

Views: 1674

Answers (1)

Micka
Micka

Reputation: 20160

your problem seems to be your input data array type. You use an int (probably 32 bit) type for your array but you use char (8 bit) type for your matrix.

please try:

char data[9]={0,1,0,0,-1,0,0,0,0};
cv::Mat m(3, 3, CV_8SC1,data);
cout<<(int)m.at<char>(0,1)<<endl;
cout<<(int)m.at<schar>(0,1)<<endl;

If you want or have to use the int array, try

int data[9]={0,1,0,0,-1,0,0,0,0};
cv::Mat m(3, 3, CV_32SC1,data);
cout<<(int)m.at<int>(0,1)<<endl;

Upvotes: 2

Related Questions