OpenCV 是Open Computer Vision的简称,因此该库主要用于计算机视觉方面。我这里用到它,是想用SVD,最小二乘法解决线性方程组。
Introduction to programming with OpenCV
http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/opencv-intro.html
how to install OpenCV 2.1.0 with Visual Studio 2008
http://opencv.willowgarage.com/wiki/VisualC%2B%2B
#include "stdafx.h" #include <iostream> using namespace std; #include <cv.h> #include <highgui.h> #include <stdio.h> int main() { //1. initialize a matrix with an array //double a[4] = {1, 1, 2, 1}; // for initializing a matrix double a[4]; CvMat Ma = cvMat(2, 2, CV_32FC1, a); //create a matrix //2. set matrix values through an array a[0] = 1; a[1] = 1; a[2] = 2; a[3] = 1; //3. define a pointer pointing to the matrix data double *pData = Ma.data.db; for (int i = 0; i < Ma.rows; ++i) { for (int j = 0; j < Ma.cols; ++j) { //4. access matrix values through the defined pointer cout << pData[i * Ma.cols + j] << "/t"; } cout << endl; } return 0; }
#include "stdafx.h" #include <iostream> using namespace std; #include <cv.h> #include <highgui.h> #include <stdio.h> void PrintMatrix(CvMat *Matrix,int Rows,int Cols) { for(int i=0;i<Rows;i++) { for(int j=0;j<Cols;j++) { printf("%.2f ",cvGet2D(Matrix,i,j).val[0]); } printf("/n"); } } int main() { double a[] = {1,1,1,1,0,1}; CvMat *coeffMatrixA = cvCreateMat(2, 3, CV_64FC1); cvSetData(coeffMatrixA, a, coeffMatrixA->step); double b[] = {3, 2}; CvMat *MatrixB = cvCreateMat(2, 1, CV_64FC1); // create a matrix,这里用CV_64FC1, cvSolve()才成功 cvSetData(MatrixB, b, MatrixB->step); // assign values for a matrix with an array //solving AX = b, using function: cvSolove() CvMat *MatrixX_solve = cvCreateMat(3, 1, CV_64FC1); cvSolve(coeffMatrixA, MatrixB, MatrixX_solve, CV_SVD); // printf("/nMatrixX_solve/n"); PrintMatrix(MatrixX_solve,MatrixX_solve->rows,MatrixX_solve->cols); //对系数矩阵进行SVD分解 CvMat *W = cvCreateMat(2, 3, CV_64FC1);//对称矩阵 CvMat *U = cvCreateMat(2, 2, CV_64FC1); CvMat *V = cvCreateMat(3, 3, CV_64FC1); cvSVD(coeffMatrixA, W, U, V); printf("/nW/n"); PrintMatrix(W,W->rows,W->cols); printf("/nU/n"); PrintMatrix(U,U->rows,U->cols); printf("/nV/n"); PrintMatrix(V,V->rows,V->cols); printf("/nValid/n"); //solving AX = b, using function: cvSVBkSb(), 对于矩阵是奇异矩阵,用这种方法比较好 CvMat *MatrixX_wuv = cvCreateMat(3, 1, CV_64FC1); cvSVBkSb(W, U, V, MatrixB, MatrixX_wuv, 0); // 该函数最后一个参数要与S, V, D分解函数所对应的参数一致。 printf("/nMatrixX_wuv/n"); PrintMatrix(MatrixX_wuv,MatrixX_wuv->rows,MatrixX_wuv->cols); returen 0; }