CvMat()函数是OpenCV 中重要的矩阵变换函数,使用方法为cvMat* cvCreateMat ( int rows, int cols, int type );
这里type可以是任何预定义类型。
1、初始化矩阵:
方式一、逐点赋值式:
CvMat*mat = cvCreateMat( 2, 2, CV_64FC1 );// 64FC1 for double,64位浮点型数据
cvZero( mat );//全为0
cvmSet( mat, 0, 0, 1 );
cvmSet( mat, 0, 1, 2 );
cvmSet( mat, 1, 0, 3 );
cvmSet( mat, 1, 1, 4 );
cvReleaseMat( &mat );
方式二、连接现有数组式:
double a[ ] = { 1, 2, 3, 4,5, 6, 7, 8,
9, 10, 11, 12 };
CvMat mat = cvMat( 3, 4, CV_64FC1, a ); //把数组a赋给矩阵mat
// 不需要cvReleaseMat,因为数据内存分配是由double定义的数组进行的。
2、IplImage 到cvMat的转换
方式一、cvGetMat方式:
CvMat mathdr;
CvMat *mat = cvGetMat( img, &mathdr );
方式二、cvConvert方式:
IplImage *img;
CvMat *mat =cvCreateMat( img->height, img->width, CV_64FC3 );
cvConvert( img, mat ); // #define cvConvert( src, dst ) cvConvertScale( (src), (dst), 1, 0 )
3、cvArr(IplImage或者cvMat)转化为cvMat
方式一、cvGetMat方式:
int coi = 0;
cvMat *mat = (CvMat*)arr;
if( !CV_IS_MAT(mat) )
{
mat = cvGetMat( mat, &matstub, &coi );
if (coi != 0) reutn; // CV_ERROR_FROM_CODE(CV_BadCOI);
}
写成函数为:
// This is just an example of function to support both IplImage and cvMat as an input
CVAPI( void ) cvIamArr( const CvArr* arr )
{
CV_FUNCNAME( "cvIamArr" );
__BEGIN__;
CV_ASSERT( mat == NULL );
CvMat matstub, *mat = (CvMat*)arr;
int coi = 0;
if( !CV_IS_MAT(mat) )
{
CV_CALL( mat = cvGetMat( mat,&matstub, &coi ) );
if (coi != 0)CV_ERROR_FROM_CODE(CV_BadCOI);
}
// Process as cvMat
__END__;
}
4、图像直接操作
方式一:直接数组操作 int col, row, z;
uchar b, g, r;
for( row = 0; row < img->height; row++ )
{
for ( col = 0; col < img->width; col++ )
{
b = img->imageData[img->widthStep * row + col *3]
g = img->imageData[img->widthStep * row + col *3 + 1];
r = img->imageData[img->widthStep * row + col *3 + 2];
}
}
方式二:宏操作:
int row, col;
uchar b, g, r;
for( row = 0; row < img->height; row++ )
{
for ( col = 0; col < img->width; col++ )
{
b = CV_IMAGE_ELEM( img, uchar, row, col * 3 );
g = CV_IMAGE_ELEM( img, uchar, row, col * 3 + 1 );
r = CV_IMAGE_ELEM( img, uchar, row, col * 3 + 2 );
}
}
注:CV_IMAGE_ELEM(pImage, uchar, i, j) = CV_MAT_ELEM(*mat, uchar, i, j)
CV_IMAGE_ELEM(img, uchar, row, col * img->nChannels + ch )
见电脑E/2011/学习OpenCV