OpenCV学习笔记(10)CvMat 与 STL vector 的格式转换与数据读写

用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);

你可能感兴趣的:(OpenCV学习笔记(10)CvMat 与 STL vector 的格式转换与数据读写)