学习过程参考opencvchina庞峰的视频教程。
主要用到ptr模板函数来获取图像文件内容的指针。把一幅图像看成是一个行向量,然后通过指针偏移历遍图像。
- //使用单循环的方式 将图像image赋值为白色
- void setAllWhiteE(Mat& image)
- {
- int x;
-
- //把二维矩阵 image看成是1*length的一维向量
- int length = image.cols*image.channels()*image.rows;
-
- //获取矩阵数据的起始地址
- uchar* data = image.ptr<uchar>(0);
-
- ///逐个访问一维向量中的元素
- for(x =0;x<length;x++)
- {
- data[x] = 255;
- }
- }
- //使用双循环的方式 将图像image赋值为白色
- void setAllWhite(Mat& image)
- {
- int x,y;
-
- //计算图像一行需要被赋值的个数
- int rowLength = image.cols*image.channels();
-
- for(y=0;y<image.rows;y++)
- {
- //获取第行的起始地址
- uchar* data = image.ptr<uchar>(y);
-
- //对第y行逐个赋值
- for(x=0;x<rowLength;x++)
- {
- *data++=255;
- }
- }
- }
比较不同方法的用时,可以参考下面的代码
- //比较 两种方法的运行速度
- void compareTime(Mat& image)
- {
- int count = 100000;
- long begin,end;
-
- //统计双循环方式运行count次需要的时间
- begin = clock();
- while(count-->0)
- setAllWhite(image);
- end = clock();
-
- //输出时间
- printf("time is %f \n",(double)(end-begin)/(double)CLOCKS_PER_SEC);
-
- //统计单循环方式运行count次需要的时间
- count = 100000;
- begin = clock();
- while(count-->0)
- setAllWhiteE(image);
- end = clock();
-
- //输出时间
- printf("time is %f \n",(double)(end-begin)/(double)CLOCKS_PER_SEC);
-
-
- }