【OpenCV】Mat的初始化


【参考链接】
https://docs.opencv.org/4.0.1/d6/d6d/tutorial_mat_the_basic_image_container.html
此为OpenCV的官方教程,英文版,浏览器有翻译功能的话可以翻译来看,整体大概还是看得懂的。

一、初始化设值

例一

直接进入正题,先给出两种使用构造函数初始化矩阵的例子:

Mat M(2, 2, CV_8UC3, Scalar(0, 0, 255));

其中第三个参数,其设计格式如下:

CV_ [每个项目的位数] [有符号或无符号] [类型前缀] C [通道数量]

u代表unsigned无符号,C代表char类型前缀通道数量最大为4,最小为1
输出结果为

[  0,   0, 255,   0,   0, 255;
   0,   0, 255,   0,   0, 255]

以上示例建立的是一个二维三通道的图像矩阵,大小为2×(2×3),2行6列,每三列代表B、G、R(在OpenCV中的标准是BGR,而不是RGB),所以输出图像为一个2×2像素的红色图,如下(图为VS2017运行过程中使用Image Watch插件显示的)。
在这里插入图片描述


例二

int sz[3] = {2, 2, 2};
Mat L(3, sz, CV_8UC(1), Scalar::all(0));

上面的示例显示了如何创建具有二维及以上维度的矩阵。sz数组指定了每一维的大小,均为2,Scalar::all(0)使每个像素点的灰度值均为0。二维以上的矩阵无法输出,所以这里就不给出输出结果了。

二、非初始化设值

下面给出使用函数的方法来实现给矩阵赋值:

例一

Mat M;
M.create(4,4, CV_8UC(2));

原文解释:

You cannot initialize the matrix values with this construction. It
will only reallocate its matrix data memory if the new size will not
fit into the old one.

我的翻译:

你无法使用此构造初始化矩阵值。如果新Mat的大小size与旧的Mat的大小size不匹配,使用该函数会重新分配内存构建一个Mat。

Mat E = Mat::eye(4, 4, CV_64F);
	cout << "E = " << endl << "" << E << endl << endl;
	Mat O = Mat::ones(2, 2, CV_32F);
	cout << "O = " << endl << "" << O << endl << endl;
	Mat Z = Mat::zeros(3, 3, CV_8UC1);
	cout << "Z = " << endl << "" << Z << endl << endl;

以上的输出结果如下
在这里插入图片描述

例二

原文:

For small matrices you may use comma separated initializers or
initializer lists (C++11 support is required in the last case):

机翻:
对于小型矩阵,你可以使用逗号分隔的初始值设定项或初始化列表(在后一种情况下需要C ++ 11支持):

Mat C = (Mat_ <double>(3, 3) << 0, - 1, 0, - 1, 5, - 1, 0, - 1, 0);
cout << "C = " << endl << "" << C << endl << endl;
C = (Mat_ <double>({ 0, - 1,0, - 1,5, - 1,0, - 1,0 })).reshape(3);
cout << "C = " << endl << "" << C << endl << endl;

输出结果如下:
在这里插入图片描述](https://img-blog.csdnimg.cn/20190417211511730.png)![在这里插入图片描述

例三

原文:

Create a new header for an existing Mat object and cv::Mat::clone or
cv::Mat::copyTo it.

机翻:
为现有Mat对象创建一个新头,cv :: Mat :: clone或cv :: Mat :: copyTo它。

Mat RowClone = C.row(1).clone();
cout << "RowClone = " << endl << "" << RowClone << endl << endl;

输出结果如下
在这里插入图片描述

例四

原文:

You can fill out a matrix with random values using the cv::randu()
function. You need to give the lower and upper value for the random
values:

机翻+修正:

你可以使用cv::randu()函数填充具有随机值的矩阵,你需要为随机值指定最低和最高值:

Mat R = Mat(3, 2, CV_8UC3);
randu(R,Scalar::all(0),Scalar::all(255));

多次输出结果均如下,是伪随机:
在这里插入图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值