Ask Your Question

read 2d array into opencv mat

asked 2013-03-08 08:38:38 -0600

BMR gravatar image

i need to read dynamic two dimensional array in opencv mat

int main()
Mat matrix;
double **theArray;
int numOfRows,numOfCols;

cin >> numOfRows ;
cin >> numOfCols ;

theArray = AllocateDynamicArray<double>(numOfRows,numOfCols);

matrix = Mat(numOfRows,numOfCols,CV_64FC1,&theArray);

string filename = "IN.xml";
FileStorage fs1(filename, FileStorage::WRITE);, FileStorage::WRITE);
fs1 << "locsINMat"          << matrix;  
fs1 << "descriptorsINMat"   << matrix;
cout << "---------------------" << endl;


template <typename T> 
T **AllocateDynamicArray( int nRows, int nCols)
      T **dynamicArray;

      dynamicArray = new T*[nRows];
      for( int i = 0 ; i < nRows ; i++ )
      dynamicArray[i] = new T [nCols];

      return dynamicArray;

template <typename T>
void FreeDynamicArray(T** dArray)
      delete [] *dArray;
      delete [] dArray;

i get this exception: Unhandled exception at 0x5d08f1aa in GP.exe: 0xC0000005: Access violation reading location 0x003f4000.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2013-03-08 09:57:29 -0600

berak gravatar image

updated 2013-03-08 09:59:43 -0600

i see a problem here:

matrix = Mat(numOfRows,numOfCols,CV_64FC1,&theArray);

if it is: double **theArray; and you take the adress of that, that's a triple pointer already .

but why **pointers at all ? the Mat() constructor there expects a uchar* pointing to consecutive memory, what you've got is an array of pointers.

edit flag offensive delete link more


double **theArray; i do that for the array to be dynamic is there another solution??

BMR gravatar imageBMR ( 2013-03-08 10:03:56 -0600 )edit

just use a single pointer, double* arr = new double[numOfRows*numOfCols]

and access that as arr[ row*numOfCols +col ] instead of theArray[row][col]

and then, pass it is 'as is': matrix = Mat(numOfRows,numOfCols,CV_64FC1,(uchar*)arr);

be careful, the Mat has no refcount for that memory, you can only destroy the arr data after you're done using the Mat ! also, it won't free the data on it's own

your example code there is a bit 'constructed', i have to say ..

berak gravatar imageberak ( 2013-03-08 10:15:43 -0600 )edit

Question Tools


Asked: 2013-03-08 08:38:38 -0600

Seen: 21,752 times

Last updated: Mar 08 '13