文章目录
Mat不但是一个非常有用的图像容器类,也是一个通用的矩阵类,可以用它来创建和操作多维矩阵.
创建Mat对象有多种方法
一、使用Mat()构造函数
使用构造函数
Mat(int rows, int cols, int type, const Scalar& s);
例:
using namespace cv;
int main() {
Mat M(2, 2, CV_8UC3, Scalar(0,0,255));
std::cout << M << std::endl;
// cout
// [ 0, 0, 255, 0, 0, 255;
// 0, 0, 255, 0, 0, 255]
std::cout << "hello world" << std::endl;
return 0;
}
二、在C\C++中通过构造函数进行初始化
下面演示了如何创建一个超过二维的矩阵
此处使用了Mat的构造函数
Mat(int ndims, const int* sizes, int type, const Scalar& s);;
例:
int main() {
int sz[3] = {2, 2, 2};
Mat L(3, sz, CV_8UC1, Scalar::all(0));
}
三、利用Create()函数
利用Mat类中的Create()成员函数进行Mat类的初始化操作
注意,此创建方法不能为矩阵设置初始值,只是改变尺寸时重新为矩阵数据开辟内存而已.
这边是调用内联函数
inline
void Mat::create(int _rows, int _cols, int _type)
{
_type &= TYPE_MASK;
if( dims <= 2 && rows == _rows && cols == _cols && type() == _type && data )
return;
int sz[] = {_rows, _cols};
create(2, sz, _type);
}
例:
using namespace cv;
using namespace std;
int main() {
Mat M;
M.create(4,4,CV_8UC(2));
}
四、采用Matlab样式初始化方式
Mat E = Mat::eye(4, 4, CV_64F);
//单位矩阵 cout [1, 0, 0, 0;
// 0, 1, 0, 0;
// 0, 0, 1, 0;
// 0, 0, 0, 1]
Mat O = Mat::ones(3,3,CV_32F);
Mat Z = Mat::zeros(3,3,CV_32F);
五、对小矩阵使用逗号分隔式初始化函数
int main() {
Mat C = (Mat_<double>(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
std::cout << C << std::endl;
}
代码输出
[0, -1, 0;
-1, 5, -1;
0, -1, 0]
六、为已存在的对象创建新信息头
int main() {
Mat C = (Mat_<double>(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
Mat rowClone = C.row(1).clone();
std:cout << rowClone << std::endl; // cout [-1, 5, -1]
}