opencv——mat操作

来源:互联网 发布:全网络大区什么意思 编辑:程序博客网 时间:2024/05/17 22:38
Code:
  1. //function: the mat operation   
  2. // data:12 /20   
  3. #include <cv.h>   
  4. #include <highgui.h>   
  5. #include <iostream.h>   
  6. void PrintMat(CvMat *mat)   
  7. {   
  8.     int i;   
  9.     int j;   
  10.     for (i=0; i<mat->rows; i++)   
  11.     {   
  12.         // the type of mat_depth   
  13.         switch (CV_MAT_DEPTH(mat->type))   
  14.         {   
  15.         case CV_32F:   
  16.         case CV_64F:   
  17.             //printf("aa");   
  18.             for (j=0; j<mat->cols; j++)   
  19.             {   
  20.                 printf("%5.2f", (float)cvGetReal2D(mat, i,j));   
  21.                 //printf("%5.5f", (float)CV_MAT_ELEM(*mat, double, i,j));   
  22.             }   
  23.             break;   
  24.         case CV_8U:   
  25.         case CV_16U:   
  26.             for (j=0; j<mat->cols; j++)   
  27.                 printf("%d", (int)cvGetReal2D(mat,i,j));   
  28.             break;   
  29.         }   
  30.         printf("/n");   
  31.     }   
  32. }   
  33. int main(int argc, char* argv[])   
  34. {   
  35.     // create mat    
  36.         CvMat *myMat=cvCreateMat(2,2, CV_32FC1);   
  37.   
  38.         float mata[] = {   
  39.                         1,2,3,   
  40.                         4,5,6,7,   
  41.                         8,9,10};   
  42.   
  43.         float matb[] = {1,1,1,   
  44.                         1,1,1,   
  45.                         1,1,1};   
  46.         float matc[9];   
  47.         CvMat Mata;   
  48.         CvMat Matb;   
  49.         CvMat Matc;   
  50.         // initial mat header   
  51.         cvInitMatHeader(&Mata, 3,3, CV_32FC1, mata, CV_AUTOSTEP);   
  52.         cvInitMatHeader(&Matb, 3,3, CV_32FC1, matb, CV_AUTOSTEP);   
  53.         cvInitMatHeader( &Matc, 3, 3, CV_32FC1, matc, CV_AUTOSTEP );   
  54.   
  55.         // print mat's element   
  56.         printf("print the mata:/n");   
  57.         PrintMat(&Mata);   
  58.         printf("print the matb:/n");   
  59.         PrintMat(&Matb);   
  60.   
  61.         // Mat add function   
  62.         cvAdd(&Mata,&Matb, &Matc, NULL);   
  63.   
  64.         //print the result    
  65.         printf("print the matc:/n");   
  66.         PrintMat(&Matc);   
  67.   
  68.         int i;   
  69.         int j;   
  70.         // enter the numbers to the mat   
  71.         for ( i = 0; i<myMat->rows; i++ )   
  72.             for ( j = 0; j <myMat->cols; j++)   
  73.             {   
  74.                    
  75.              scanf("%f", &CV_MAT_ELEM(*myMat, float , i , j));   
  76.                 //cin >> CV_MAT_ELEM(*myMat, float , i , j);   
  77.             }   
  78.   
  79.             // print mat element   
  80.     PrintMat(myMat);   
  81.     printf("Hello World!/n");   
  82.     return 0;   
  83. }