前段时间,我为一个项目编写了以下 C 代码。它有点过时,但它适用于 matlab 2011a。如果没有别的,它应该作为一个例子。它确实做出了许多假设 - 大部分都记录在案。
输入参数是要写入的文件名、指向 CvMat 的指针数组、这些矩阵的名称数组以及要写入的矩阵数。
void writeMatFile( const char *fileName, CvMat ** matrices, const char **names, int numMatrices ) {
FILE *file = fopen( fileName, "wb" );
for( int i=0; i<numMatrices; i++ ) {
CvMat * mat = matrices[i];
const char *name = names[i];
// If mat is ND we write multiple copies with _n suffixes
int depth = CV_MAT_CN(mat->type);
for( int d=0; d<depth; d++ ) {
// Assumption that we are always dealing with double precision
uint32_t MOPT = 0000;
fwrite(&MOPT, 1, sizeof( uint32_t), file);
uint32_t mrows = mat->rows;
uint32_t ncols = mat->cols;
uint32_t imagef = 0;
char nameBuff[ strlen( name ) + 10];
strcpy(nameBuff, name);
if( depth>1) {
char suffix[5];
sprintf(suffix, "_L%d", d+1);
strcat(nameBuff, suffix);
}
uint32_t nameLength = strlen( nameBuff ) + 1;
fwrite( &mrows, 1, sizeof( uint32_t), file);
fwrite( &ncols, 1, sizeof( uint32_t), file);
fwrite( &imagef, 1, sizeof( uint32_t), file);
fwrite( &nameLength, 1, sizeof( uint32_t), file);
fwrite( nameBuff, nameLength, 1, file );
for( int col = 0; col<ncols; col++ ) {
for( int row=0; row<mrows; row++ ) {
CvScalar sc = cvGet2D(mat, row, col);
fwrite(&(sc.val[d]), 1, sizeof( double ), file);
}
}
}
}
fclose( file );
}