Usually, OpenCV is used for computer vision applications. The friends who are familiar with computer vision must know how important is the linear algebra for computer vision, specially the matrix operations. As we know, by C++ programming, the assit about matrix calculation is always scarce. We are able to use array or vector data types to handle the matrix operation but at any rate it is not a efficient and intuitive method. But luckily with OpenCV library we are in the position to do the most of matrix calculations like adding matrix, getting the dimension or size of a matrix and so on. Here is a short introduction of some relevant matrix operations in OpenCV. Today I will give an example of how to calculata a SVD(singular value decomposision) of a matrix.
#include "cv.h"
#include <stdio.h>
void main()
{
CvMat* mat = cvCreateMat(3,3,CV_32FC1);
cvZero(mat);
CV_MAT_ELEM( *mat, float, 0, 0 ) = 0.23839f;
CV_MAT_ELEM( *mat, float, 0, 1 ) = 0.957069f;
CV_MAT_ELEM( *mat, float, 0, 2 ) = 0.16489f;
CV_MAT_ELEM( *mat, float, 1, 0 ) = -0.101391f;
CV_MAT_ELEM( *mat, float, 1, 1 ) = 0.934907f;
CV_MAT_ELEM( *mat, float, 1, 2 ) = 0.340102f;
CV_MAT_ELEM( *mat, float, 2, 0 ) = 0.171344f;
CV_MAT_ELEM( *mat, float, 2, 1 ) = -0.0977953f;
CV_MAT_ELEM( *mat, float, 2, 2 ) = 0.31991f;
CvMat* U = cvCreateMat(3,3,CV_32FC1);
CvMat* D = cvCreateMat(3,3,CV_32FC1);
CvMat* V = cvCreateMat(3,3,CV_32FC1);
CvMat* Result = cvCreateMat(3,3,CV_32FC1);
cvSVD(mat, D, U, V, CV_SVD_V_T); // A = U D V^T
cvMatMul(U,V,Result);
float element1 = CV_MAT_ELEM(*Result,float,0,0);
printf("%f\n",element1);
float element2 = CV_MAT_ELEM(*Result,float,0,1);
printf("%f\n",element2);
float element3 = CV_MAT_ELEM(*Result,float,0,2);
printf("%f\n",element3);
float element4 = CV_MAT_ELEM(*Result,float,1,0);
printf("%f\n",element4);
float element5 = CV_MAT_ELEM(*Result,float,1,1);
printf("%f\n",element5);
float element6 = CV_MAT_ELEM(*Result,float,1,2);
printf("%f\n",element6);
float element7 = CV_MAT_ELEM(*Result,float,2,0);
printf("%f\n",element7);
float element8 = CV_MAT_ELEM(*Result,float,2,1);
printf("%f\n",element8);
float element9 = CV_MAT_ELEM(*Result,float,2,2);
printf("%f\n",element9);
}
typedef struct CvMat
{
int type;
int step;
/* for internal use only */
int* refcount;
int hdr_refcount;
union
{
uchar* ptr;
short* s;
int* i;
float* fl;
double* db;
} data;
ontheweg
Posted in: 

0 comments:
Post a Comment