Mat对象

Mat对象与IplImage对象的区别

Mat对象OpenCV2.0之后引进的图像数据结构、自动分配内存、不存在内存泄漏的问题,是面向对象的数据结构。分了两个部分,头部与数据部分。
IplImage是从2001年OpenCV发布之后就一直存在,是C语言风格的数据结构,需要开发者自 己分配与管理内存,对大的程序使用它容易导致内存泄漏问题。

Mat对象使用

在这里插入图片描述

常用方法:
void copyTo(Mat mat)
void convertTo(Mat dst, int type)
Mat clone()
int channels()
int depth()
bool empty();
uchar* ptr(i=0)
  • 输出图像的内存是自动分配的

  • 使用OpenCV的C++接口,不需要考虑内存分配问题

  • 赋值操作和拷贝构造函数只会复制头部分

  • 使用clone与copyTo两个函数实现数据完全复制

    1.dst = src.clone();

    2.src.copyTo(dst);

Mat定义数组

cv::Mat::Mat构造函数
Mat M(2,2,CV_8UC3, Scalar(0,0,255))
其中前两个参数分别表示行(row)跟列(column)、第三个CV_8UC3中的8表示每个通道占8位、U表示无符号、C表示Char类型、3表示通道数目是3,第四个参数是向量表示初始化每个像素值是多少,向量长度对应通道数目一致。

1.
Mat dst;
dst = Mat(src.size(), src.type());//初始化Mat对象dst大小类型跟src一样
dst = Scalar(127, 0, 255);//赋值3个通道BGR(红色),0为黑色,全255为白色。
2.
Mat M(3, 3, CV_8UC3, Scalar(127, 0, 255)); //3*3的像素集合,每个像素有3个通道BGR,第1 2通道为0,第3通道为255
3.
Mat M(3, 3, CV_8UC1, Scalar(127)); //1个通道,127灰色

创建多维数组cv::Mat::create
创建多维数组cv::Mat::create

int sz[3] = {2,2,2};     
Mat  L(3,sz, CV_8UC1, Scalar::all(0));
Mat M;
M.create(4, 3, CV_8UC2);
M = Scalar(127,127);
cout << "M = " << endl << " " << M << endl << endl;
uchar* firstRow = M.ptr<uchar>(0);
printf("%d", *firstRow);
Mat kernel = (Mat_<float>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0); //定义小数组
cout << "kernel = " << endl << " " << kernel << endl << endl;

演示代码

#include <opencv2/core/core.hpp> 
#include <opencv2/imgcodecs.hpp> 
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;
int main(int argc, char** args) {
Mat image = imread("D:/test.jpg", IMREAD_GRAYSCALE);
if (image.empty()) {
cout << "could not find the image resource..." << std::endl;
return -1;
}
namedWindow("My Image", CV_WINDOW_AUTOSIZE);
imshow("My Image", image);

Mat M;
M.create(4, 3, CV_8UC2);
M = Scalar(127,127);
cout << "M = " << endl << " " << M << endl << endl;
uchar* firstRow = M.ptr<uchar>(0);
printf("%d\n", *firstRow);

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

waitKey(0);
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值