矩阵处理
1、矩阵的内存分配与释放
(1) 总体上:
(2) 为新矩阵分配内存:
CvMat* cvCreateMat(int rows, int cols, int type);
CvMat* M = cvCreateMat(4,4,CV_32FC1);
(3) 释放矩阵内存:
CvMat* M = cvCreateMat(4,4,CV_32FC1);
cvReleaseMat(&M);
(4) 复制矩阵:
CvMat* M1 = cvCreateMat(4,4,CV_32FC1);
CvMat* M2;
M2=cvCloneMat(M1);
(5) 初始化矩阵:
double a[] = { 1,
CvMat Ma=cvMat(3, 4, CV_64FC1, a);
//等价于:
CvMat Ma;
cvInitMatHeader(&Ma, 3, 4, CV_64FC1, a);
(6) 初始化矩阵为单位矩阵:
CvMat* M = cvCreateMat(4,4,CV_32FC1);
cvSetIdentity(M); // does not seem to be working properl
2、访问矩阵元素
(1) 假设需要访问一个2D浮点型矩阵的第(i, j)个单元.
(2) 间接访问:
cvmSet(M,i,j,2.0); // Set M(i,j)
t = cvmGet(M,i,j); // Get M(i,j)
(3) 直接访问(假设矩阵数据按4字节行对齐):
CvMat* M
int n
float *data = M->data.fl;
data[i*n+j] = 3.0;
(4) 直接访问(当数据的行对齐可能存在间隙时 possible alignment gaps):
CvMat* M
int
float *data = M->data.fl;
(data+i*step)[j] = 3.0;
(5) 对于初始化后的矩阵进行直接访问:
double a[16];
CvMat Ma = cvMat(3, 4, CV_64FC1, a);
a[i*4+j] = 2.0; // Ma(i,j)=2.0;
3、矩阵/向量运算
(1) 矩阵之间的运算:
CvMat *Ma, *Mb, *Mc;
cvAdd(Ma, Mb, Mc);
cvSub(Ma, Mb, Mc);
cvMatMul(Ma, Mb, Mc);
(2) 矩阵之间的元素级运算:
CvMat *Ma, *Mb, *Mc;
cvMul(Ma, Mb, Mc);
cvDiv(Ma, Mb, Mc);
cvAddS(Ma, cvScalar(-10.0), Mc); // Ma.-10 -> Mc
(3) 向量乘积:
double va[] = {1, 2, 3};
double vb[] = {0, 0, 1};
double vc[3];
CvMat Va=cvMat(3, 1, CV_64FC1, va);
CvMat Vb=cvMat(3, 1, CV_64FC1, vb);
CvMat Vc=cvMat(3, 1, CV_64FC1, vc);
double res=cvDotProduct(&Va,&Vb); // 向量点乘:
cvCrossProduct(&Va, &Vb, &Vc);
注意在进行叉乘运算时,Va, Vb, Vc 必须是仅有3个元素的向量.
(4) 单一矩阵的运算:
CvMat *Ma, *Mb;
cvTranspose(Ma, Mb);
CvScalar t = cvTrace(Ma); // 迹:trace(Ma) -> t.val[0]
double d = cvDet(Ma);
cvInvert(Ma, Mb);
(5) 非齐次线性方程求解:
CvMat* A
CvMat* x
CvMat* b
cvSolve(&A, &b, &x);
(6) 特征值与特征向量 (矩阵为方阵):
CvMat* A
CvMat* E
CvMat* l
cvEigenVV(A, E, l);
(7) 奇异值分解(SVD):====
CvMat* A
CvMat* U
CvMat* D
CvMat* V
cvSVD(A, D, U, V, CV_SVD_U_T|CV_SVD_V_T); // A = U D V^T
标志位使矩阵U或V按转置形式返回 (若不转置可能运算出错).