Opencv笔记:显式创建Mat对象的六种方法


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]


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值