OpenCV中Mat的data成员解析

来源:互联网 发布:matlab mac 破解版 编辑:程序博客网 时间:2024/04/30 07:27

 OpenCV 自2.x版本以来,处理图像的主要数据结构从CvMat变成了Mat,下面是OpenCV官方文档对Mat的描述:

class CV_EXPORTS Mat{public:// ... a lot of methods ....../*! includes several bit-fields:- the magic signature- continuity flag- depth- number of channels*/int flags;//! the array dimensionality, >= 2int dims;//! the number of rows and columns or (-1, -1) when the array has more than 2 dimensionsint rows, cols;//! pointer to the datauchar* data;//! pointer to the reference counter;// when array points to user-allocated data, the pointer is NULLint* refcount;// other members...};

       在访问和修改图像矩阵像素值的时候,我们经常会用到at,ptr,以及迭代器MatIterator等,对于用Mat存储的图像的像素值的访问方法,此篇博文已经介绍得颇为详细http://blog.csdn.net/xiaowei_cqu/article/details/7771760,本文的重点在于用data访问图像元素值的时候遇到的一些问题。图像矩阵是一个二维数组,不论是灰度图像还是彩色图像,在计算机内存中都是以一维数组的形式存储的。用Mat存储一幅图像时,若图像在内存中是连续存储的(Mat对象的isContinuous == true),则可以将图像的数据看成是一个一维数组,而其data(uchar*)成员就是指向图像数据的第一个字节的,因此可以用data指针访问图像的数据,那么问题来了,OpenCV中将data定义为uchar*,而当我们用构造函数创建一个Mat对象的时候,可以指定图像的数据类型有CV_8UC1、CV_8UC3、CV_32FC1、CV_32FC3等多种,那么我们如何通过data指针去访问和修改图像的某一个像素值呢,对于数据为uchar类型的Mat对象,可以直接用data访问和修改,对于数据为float或double类型的Mat对象,我们同样可以用data对图像的某个像素值进行访问和修改操作,方法就是将data强制转换成指向Mat对象对应数据类型的指针。例如我们创建一个10x10的CV_32FC1的Mat对象,将其每个元素都赋值为1.2f(float),然后输出每个元素的值,这里我们用data进行相关操作,代码和运行结果如下:

Mat img(10,10,CV_32FC1);
for (int i = 0; i < img.rows * img.cols; i++){   float* data = (float*)img.data;   data[i] = 1.2f;}if (img.isContinuous()){    for (int i = 0; i < img.rows * img.cols; i++)    {        float* data = (float*)img.data;        cout<<data[i]<<" ";    }}




0 0
原创粉丝点击