CV_MAT_ELEM是OpenCV中用来访问矩阵每个元素的宏,这个宏只对单通道矩阵有效,多通道会报错。
宏原型:
CV_MAT_ELEM( matrix, elemtype, row, col )
参数
matrix:要访问的矩阵
elemtype:矩阵元素的类型,不是CV_32FC1...而是float...
row:所要访问元素的行数
col:所要访问元素的列数
1.获取矩阵元素
-
#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;
-
}
扫描二维码关注公众号,回复:
4021622 查看本文章
2.初始化矩阵
-
#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;
-
-
//验证是否初始化
-
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;
-
}
PS:对多通道矩阵初始化和获取多通道矩阵的值可分别使用cvSetND和cvGetND函数,如:
-
#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;
-
}
转载自:https://blog.csdn.net/u010361581/article/details/9253039