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是每一行的字節個數