Mat对象与IplImage对象
- Mat对象是OpenCV2.0之后引进的数据结构,自动分配内存、不存在内存泄漏的问题,是面向对象的数据结构。
- IplImage是从2001年OpenCV发布之后就一直存在的,是C语言风格的数据结构,需要开发人员自己分配与管理内存,对大的程序使用它容易导致内存泄漏的问题。
=================
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) // Mat A, B; A.copyTo(B);
- void convertTo(Mat dst, int type)
- Mat clone() // Mat A ; Mat B = A.clone();
- int channels()
- int depth()
- bool empty(); 是否为空 // if(srcImg.empty()) return -1;
- uchar* ptr(i=0)
eg: const uchar *first = img.ptr<uchar>(0);
printf("value: %d",*first);
代码实例:
Mat dst;
dst = Mat(src.size(), src.type());//创建大小为size 类型为type的图像
// Scalar(127, 225, 255)是对矩阵进行初始化赋值,
// 颜色为 RGB(127, 225, 255),大小、类型与原图像相同
dst = Scalar(127, 225, 255);
namedWindow("output1", CV_WINDOW_AUTOSIZE);
imshow("output1", dst);
效果图:生成一张什么都没有的图像,颜色是RGB(127, 0, 255),大小、类型与原图像相同
综合实例:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
Mat src;
src = imread("test.jpg");
if (src.empty())//如果数组没有元素 则返回true
{
cout << "could not load image..." << endl;
return -1;
}
namedWindow("inputImg", CV_WINDOW_AUTOSIZE);
imshow("inputIMg", src);
Mat dst;
dst = Mat(src.size(), src.type());//创建大小为size 类型为type的图像
// Scalar(127, 225, 255)是对矩阵进行初始化赋值,
// 颜色为 RGB(127, 225, 255),大小、类型与原图像相同
dst = Scalar(127, 225, 255);
namedWindow("output1", CV_WINDOW_AUTOSIZE);
imshow("output1", 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("value : %d\n", *firstRow);
//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;
}
运行结果:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)