I wrote the following code:
int _tmain(int argc, _TCHAR* argv[])
{
int vals[]={1,2,3,4,5,6,7,8,9};
CvMat mat = cvMat(3,3,CV_8UC1,vals);
for(int i=0;i<mat.rows;i++)
{
int* ptr = (int*) (mat.data.ptr + i* mat.step);
for(int j=0;j<mat.cols;j++)
{
printf("%d\t",*ptr++);
}
printf("\n");
}
return 0;
}
The output I got is:
1 2 3
512 768 1024
196608 262144 327680
The matrix is not initialized properly. The pointer ptr points to the beginning of each row and incrementing it gives the element in corresponding column. Is my assumption correct? Is there any mistake with the cvMat constructor used or the access method of elements?
Why dont you use the cv::Matclass?
It has some handy functions which handle memory better.
for declaring and initializing cv::Mat in your case the code will look like this:
int main()
{
int vals[] = {1,2,3,4,5,6,7,8,9};
Mat mat = cv::Mat(3, 3, CV_8UC1, vals).clone();
for(int i = 0; i < mat.rows; i++)
{
for(int j = 0; j < mat.cols; j++)
{
cout << mat.at<uchar>(j,i) << " ";
}
cout << endl;
}
return 0;
}
Wrong. mat.data.ptr is for unsigned chars from http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/opencv-intro.html
uchar* ptr; // data pointer for an unsigned char matrix
you should use
mat.data.i
for integers
You initialize matrix properly but printing it wrong because of using the wrong pointer of data structure.
CvMat // 2D array
|-- int type; // elements type (uchar,short,int,float,double) and flags
|-- int step; // full row length in bytes
|-- int rows, cols; // dimensions
|-- int height, width; // alternative dimensions reference
|-- union data;
|-- uchar* ptr; // data pointer for an unsigned char matrix
|-- short* s; // data pointer for a short matrix
|-- int* i; // data pointer for an integer matrix
|-- float* fl; // data pointer for a float matrix
|-- double* db; // data pointer for a double matrix
See? Did this help?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With