OpenCV随笔004-使用指针及迭代器遍历图像

来源:互联网 发布:双色球缩水软件在线 编辑:程序博客网 时间:2024/04/19 22:47

     任何图像处理算法都是从操作每个像素开始的,在OpenCV中,提供了种访问每个像素的方法:使用at方法、使用迭代器、使用指针。上一篇中我们已经简单介绍了at方法,这一篇我们将使用指针来操作像素。

       下面为主程序:

#include<opencv2/core/core.hpp>#include<opencv2/highgui/highgui.hpp>using namespace cv;void colorReduce(Mat &image,Mat &result,int div);int main(){ Mat image=imread("D:/Lena.jpg");Mat result;result.create(image.rows,image.cols,image.type());namedWindow("原图");imshow("原图",image);    colorReduce(image,result,64);namedWindow("结果");imshow("结果",result);waitKey(0);return 0;}

     下面的函数是用来减少图像中的颜色数目的。

#include<opencv2/core/core.hpp>#include<opencv2/highgui/highgui.hpp>using namespace cv;void colorReduce(Mat &image,Mat &result,int div){result=image.clone();int rows = result.rows;//行数int cols = result.cols * result.channels();//每行元素个数for (int i=0;i<rows;i++){uchar* data=result.ptr<uchar>(i);//第i行的首地址for(int j=0;j<cols;j++)//处理每一个像素{data[j]=data[j]/div*div+div/2;//*data++=*data/div*div+div/2;//data[j]=data[j]-data[j]%div+div/2;}}}

      一个宽为W,高为H的彩色图像需要一个大小由W x H x 3 个uchar 构成的内存块,但是为了效率,每行会增补一些额外像素,因为行的长度是4的话,一些多媒体处理芯片可以更高效的处理图像。如果不对行进行填补的时候,图像可以视为长为W x H 的一维数组,通过cv::Mat的一个成员函数isContinuous来判断这幅图像是否对行进行了填补,如果返回值为真的话,则是没有填补,利用图像的连续性,我们可以使用一个循环就可以缩减颜色。

#include<opencv2/core/core.hpp>#include<opencv2/highgui/highgui.hpp>using namespace cv;void colorReduce(Mat &image,Mat &result,int div){result=image.clone();int rows = result.rows;//行数int cols = result.cols * result.channels();//每行元素个数if(result.isContinuous()){cols=cols*rows;rows=1;//image.reshape(1,image.cols*image.rows);}for (int i=0;i<rows;i++){uchar* data=result.ptr<uchar>(i);//第i行的首地址for(int j=0;j<cols;j++)//处理每一个像素{//data[j]=data[j]/div*div+div/2;*data++=*data/div*div+div/2;//data[j]=data[j]-data[j]%div+div/2;}}}

        迭代器是一种特殊的类,用来遍历集合中的各个元素,同时隐藏了在给定集合上的元素迭代的具体实现方式。

void colorReduce(Mat &image,Mat &result,int div){result=image.clone();Mat_<Vec3b>::iterator it=result.begin<Vec3b>();Mat_<Vec3b>::iterator itend=result.end<Vec3b>();for (;it!=itend;++it){(*it)[0] = (*it)[0]/div*div + div/2;          (*it)[1] = (*it)[1]/div*div + div/2;          (*it)[2] = (*it)[2]/div*div + div/2;}}


0 0
原创粉丝点击