Mat对象
- 一张图,在计算机中是二维数组的形式存放的,把这个数组存放在Mat对象里面,是一个数据结构
- Mat对象与IplImage对象
- Mat对象是OpenCV2.0之后引进的数据结构,自动分配内存、不存在内存泄漏的问题,是面向对象的数据结构。
- 分为两个部分,头部与数据部分
- IplImage是从2001年OpenCV发布之后就一直存在的,是C语言风格的数据结构,需要开发人员自己分配与管理内存,对大的程序使用它容易导致内存泄漏的问题
- Mat对象是OpenCV2.0之后引进的数据结构,自动分配内存、不存在内存泄漏的问题,是面向对象的数据结构。
Mat对象的构造函数与常用方法
- 构造函数:
- Mat()
- Mat(int rows,int cols,int type)
- Mat(Size size,int type)
- Mat(int rows,int cols,int type,const Scalar &s)
- Mat(Size size,int type,const Scalar &s)
- Mat(int ndims,const int *sizes,int type)
- Mat(int ndims,const int *sizes,int type,const Scalar &s)
- 常用方法:
- void copyTo(Mat mat)
- 完成复制一份
- void convertTo(Mat dst,int type)
- Mat clone()
- 完成复制一份
- int channels()
- int depth()
- 深度
- bool empty();
- 是否为空
- uchar* ptr(i=0)
- 获取按行的指针,i=0表示第0行
- void copyTo(Mat mat)
构造:
Mat dst; dst = Mat(src.size(), src.type()); //定义大小,类型 dst = Scalar(127, 0, 255); namedWindow("output", CV_WINDOW_AUTOSIZE); imshow("output", dst);
- 1
- 2
- 3
- 4
- 5
生成一张什么都没有的图像,颜色是RGB(127, 0, 255),大小、类型与原图像相同
完全拷贝:
1,克隆clone()Mat dst = src.clone();
2,copyTo()Mat dst;
//需要传一个参数
src.copyTo(dst);通道数channels()
cvtColor(src, dst, CV_BGR2GRAY); //转换为灰度图
printf("input image channels: %d\n", src.channels()); //看看有多少个通道
printf("output image channels: %d\n", dst.channels());
#include <opencv2\opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
Mat src;
src = imread("D:/demo01.jpg");
if (src.empty())//如果数组没有元素 则返回true
{
cout << "could not load image..." << endl;
return -1;
}
namedWindow("input",CV_WINDOW_AUTOSIZE);
imshow("input",src);
Mat dst;
dst = Mat(src.size(),src.type());//创建大小为size 类型为type的图像
dst = Scalar(127,255,255);//Scalar(1,3)是对矩阵进行初始化赋值
namedWindow("output", CV_WINDOW_AUTOSIZE);
imshow("output", dst);
Mat dst1;
src.copyTo(dst1);//把矩阵复制到另一个矩阵中
//openCV中image.copyTo()有两种形式:
// 1、image.copyTo(imageROI),作用是把image的内容粘贴到imageROI;
// 2、image.copyTo(imageROI,mask), 作用是把mask和image重叠以后把mask中像素值为0(black)的点对应的image中的点变为透明,而保留其他点。
namedWindow("copyTo output", CV_WINDOW_AUTOSIZE);
imshow("copyTo output", dst1);
//Mat.ptr<uchar>(row):获取第row行的图像像素指针。图像的行数从0开始计数
const uchar* firstRow = dst.ptr<uchar>(0);
printf("fist pixel value : %d\n", *firstRow);//127
//OpenCV提高了函数filter2D来实现掩膜操作
Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
filter2D(src, dst,src.depth(),kernel);
//输出 掩膜操作后的图像
namedWindow("掩膜操作后的图像", CV_WINDOW_AUTOSIZE);
imshow("掩膜操作后的图像", dst);
Mat m2 = Mat::eye(2, 2, CV_8UC1);
cout << "m2 =" << endl << m2 << endl;
namedWindow("output", CV_WINDOW_AUTOSIZE);
imshow("output", m2);
waitKey(0);
return 0;
}