Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a matrix of pixels and reshape matrix in openCV

I am implementing an image processing algorithm in C++ using openCV, in which the 1st step requires that the image be converted to a matrix. I know that when an image is loaded into openCV, it is already stored as a matrix. The image that I am using is of size 80 x 60, so I am assuming that the matrix it is stored in is of size 80 x 60. However, I would like to first be able to see this matrix and then be able to reshape it into a matrix with the same no. of pixels but as one long column instead. i.e. the 80 x 60 matrix would now become a 4800 x 1 matrix. I have tried researching textbooks and online but to no avail. This is my code so far. In any case, it is not working because I cannot cannot convert from 'IplImage *' to 'CvMat * but how else I am supposed to assign my pixel values to the matrix after creating it? Please, I would greatly appreciate if someone could help me with this code.

#include "cv.h"
#include "highgui.h"
#include "iostream"

using namespace std;
int main( int argc, char* argv ) {
IplImage* img0 = NULL;
CvMat* img0_mat = NULL ;
img0 = cvLoadImage("C:\\new\\walk mii.jpg");
if (!img0){
    return -1;}
img0_mat = cvCreateMat(80, 60, 1);
img0_mat = img0;
cout <<" matrix " << img0 << endl;

cvWaitKey(0);
return 0;
}
like image 240
sue-ling Avatar asked Nov 14 '22 09:11

sue-ling


1 Answers

You could call Mat::reshape(int cn, int rows=0):

The method makes a new matrix header for *this elements. The new matrix may have different size and/or different number of channels. Any combination is possible, as long as:

1) No extra elements is included into the new matrix and no elements are excluded. Consequently, the product

2) rows*cols*channels() must stay the same after the transformation.

No data is copied, i.e. this is O(1) operation. Consequently, if you change the number of rows, or the operation changes elements’ row indices in some other way, the matrix must be continuous. See Mat::isContinuous() .

...it looks like you're using an older version of the library though so you want cvReshape. Something like this should work:

#include "cv.h" 
#include "highgui.h" 
#include "iostream" 
using namespace std; 

int main( int argc, char* argv ) 
{ 
    IplImage* img0 = NULL; 
    CvMat* img0_mat = NULL ; 
    img0 = cvLoadImage("C:\\new\\walk mii.jpg"); 
    img0_mat = cvCreateMat(80, 60, 1); 

    CvMat row_header, *row;
    row = cvReshape( img0_mat, &row_header, 0, 1 );

    cout << " matrix " << row->tostring() << endl; 

    cvWaitKey(0); 
    return 0;
}
like image 53
Jon Cage Avatar answered Dec 22 '22 05:12

Jon Cage