将2d数组读入opencv mat

时间:2013-03-08 12:09:06

标签: opencv

我需要在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);
fs1.open(filename, FileStorage::WRITE);
fs1 << "locsINMat"          << matrix;  
fs1 << "descriptorsINMat"   << matrix;
fs1.release();
cout << "---------------------" << endl;

FreeDynamicArray(theArray);

}
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;
}

我得到这个例外: GP.exe中0x5d08f1aa处的未处理异常:0xC0000005:访问冲突读取位置0x003f4000。

1 个答案:

答案 0 :(得分:2)

float data[2][5] = {{1,2,3,4,5},{7,8,9,10,11}}; 
A = Mat(2, 5, CV_32FC1, &data);

不会抛出任何错误。你的行和列是否正确?

对于动态内存分配: 我认为内存分配应该这样做:

double **theArray;
theArray= (double**)malloc(numOfRows* sizeof(double*));

for(i = 0; i < numOfRows; i++)
  theArray[i] = (double*)malloc(numOfCols* sizeof(double));