当前位置: 代码迷 >> 综合 >> OpenCV學習筆記(10)CvMat 與 STL vector 的格式轉換與數據讀寫
  详细解决方案

OpenCV學習筆記(10)CvMat 與 STL vector 的格式轉換與數據讀寫

热度:72   发布时间:2023-12-16 02:45:48.0

http://blog.csdn.net/chenyusiyuan/article/details/5042765

用STL vector來進行數組的數據讀寫非常方便,可以動態調整數組大小,不過在OpenCV裡使用vector時,要保存vector數組的數據,就需要轉換為 CvMat 格式。 
比如有一個雙通道數組:

vector points[2];

可以按如下方式來保存數據:

int len = points[0].size();
CvMat* pts = cvCreateMat(2,len,CV_32FC2);
for (i=0;i<2;i++)for (j=0;j<len;j++){((float*)(pts->data.ptr + pts->step*i))[j*2] = points[i][j].x;((float*)(pts->data.ptr + pts->step*i))[j*2+1] = points[i][j].y;}
CvFileStorage* fs = cvOpenFileStorage( "data.xml", 0, CV_STORAGE_WRITE);
cvWrite(fs, "points_matrix", pts);
cvReleaseFileStorage(&fs); 

反之,從本地xml文件中讀入CvMat數組,再轉換為 vector 格式,方式如下:

CvFileStorage* fs = cvOpenFileStorage( "data.xml", 0, CV_STORAGE_READ);
CvMat* pts = (CvMat*)cvReadByName(fs, 0, "points_matrix");
CvSize pts_size = cvGetSize(pts);
points[0].resize(pts_size.width);
points[1].resize(pts_size.width);
for (i=0;i<2;i++)for (j=0;j<pts_size.width;j++){points[i][j].x = ((float*)(pts->data.ptr + pts->step*i))[j*2];points[i][j].y = ((float*)(pts->data.ptr + pts->step*i))[j*2+1];}
cvReleaseFileStorage(&fs);

  相关解决方案