CV_MAT_ELEM是OpenCV中用來訪問矩陣每個(gè)元素的宏,,這個(gè)宏只對(duì)單通道矩陣有效,,多通道會(huì)報(bào)錯(cuò)。
宏原型:
CV_MAT_ELEM( matrix, elemtype, row, col )
參數(shù)
matrix:要訪問的矩陣
elemtype:矩陣元素的類型,,不是CV_32FC1...而是float...
row:所要訪問元素的行數(shù)
col:所要訪問元素的列數(shù)
1.獲取矩陣元素
- <span style="font-family:Microsoft YaHei;font-size:14px;">#include "highgui.h"
- #include "cv.h"
- #include <iostream>
-
- int main()
- {
- float a[]={1,2,3,
- 4,5,6,
- 7,8,9};
- CvMat mat=cvMat(3,3,CV_32FC1,a);
-
- for(int i=0;i<3;i++)
- {
- for (int j=0;j<3;j++)
- {
- cout<<CV_MAT_ELEM(mat,float,i,j)<<endl;
- }
- }
-
- float b=CV_MAT_ELEM(mat,float,0,2);
- cout<<"b="<<b<<endl;
-
- return 0;
- }</span>
2.初始化矩陣
- <span style="font-size:14px;">#include "highgui.h"
- #include "cv.h"
- #include <iostream>
-
- int main()
- {
- CvMat* mat=cvCreateMat(2,2,CV_32FC1);
-
- CV_MAT_ELEM(*mat,float,0,0)=1;
- CV_MAT_ELEM(*mat,float,0,1)=2;
- CV_MAT_ELEM(*mat,float,1,0)=3;
- CV_MAT_ELEM(*mat,float,1,1)=4;
-
- //驗(yàn)證是否初始化
- for(int i=0;i<2;i++)
- {
- for (int j=0;j<2;j++)
- {
- cout<<CV_MAT_ELEM(*mat,float,i,j)<<endl;
- }
- }
-
- return 0;
- }</span>
PS:對(duì)多通道矩陣初始化和獲取多通道矩陣的值可分別使用cvSetND和cvGetND函數(shù),,如:
- <span style="font-size:14px;">#include "highgui.h"
- #include "cv.h"
- #include <iostream>
-
- int main()
- {
- CvMat* mat=cvCreateMat(2,2,CV_32FC2);
- cvSet2D(mat,0,0,cvScalar(10,10,0,0));
-
- CvScalar b=cvGet2D(mat,0,0);
- cout<<b.val[0]<<endl<<b.val[1]<<endl;
-
- return 0;
- }</span>
|