OpenCV 读写CvMat到文件中以及从文件之中都去数据:
int cvx_dump_vector(CvMat *mat,char *filename,int type){
int i,j;
FILE *fp=fopen(filename,"w+");
if(fp!=NULL){
fprintf(fp,"%d %d\n",mat->rows,mat->cols);
for(i=0;i<mat->rows;i++){
for(j=0;j<mat->cols;j++){
switch(type)
{
case 0:
fprintf(fp,"%d ",(mat->data.i+i*mat->step/4)[j]);
break;
case 1:
fprintf(fp,"%f ",(mat->data.fl+i*mat->step/4)[j]);
break;
case 2:
fprintf(fp,"%lf ",(mat->data.db+i*mat->step/8)[j]);
break;
}
}
fprintf(fp,"\n");
}
fclose(fp);
}
return 0;
}
CvMat *cvx_load_vector(char* filename,int type){
int rows,cols,i,j;
CvMat *mat=NULL;
FILE *fp=fopen(filename,"r+");
if(fp!=NULL){
fscanf(fp,"%d %d",&rows,&cols);
switch(type){
case 0:
mat=cvCreateMat(rows,cols,CV_32SC1);
break;
case 1:
mat=cvCreateMat(rows,cols,CV_32FC1);
break;
case 2:
mat=cvCreateMat(rows,cols,CV_64FC1);
break;
}
for(i=0;i<mat->rows;i++){
for(j=0;j<mat->cols;j++){
switch(type)
{
case 0:
fscanf(fp,"%d",&(mat->data.i+i*mat->step/4)[j]);
break;
case 1:
fscanf(fp,"%f",&(mat->data.fl+i*mat->step/4)[j]);
break;
case 2:
fscanf(fp,"%lf",&(mat->data.db+i*mat->step/8)[j]);
break;
}
}
}
fclose(fp);
}
return mat;
}
一定要注意和IplImage直接操作元素的方式的不同,IplImage的数据是一个uchar*类型,而CvMat数据是一个union类型,含有不同类型的指针。step是每一行的字节个数