OpenCV2学习笔记---指针方式历遍图像

学习过程参考opencvchina庞峰的视频教程。

主要用到ptr模板函数来获取图像文件内容的指针。把一幅图像看成是一个行向量,然后通过指针偏移历遍图像。

  1. //使用单循环的方式 将图像image赋值为白色
  2. void setAllWhiteE(Mat& image)
  3. {
  4.         int x;

  5.         //把二维矩阵 image看成是1*length的一维向量
  6.         int length = image.cols*image.channels()*image.rows;

  7.         //获取矩阵数据的起始地址
  8.         uchar* data = image.ptr<uchar>(0);

  9.         ///逐个访问一维向量中的元素
  10.         for(x =0;x<length;x++)
  11.         {
  12.                 data[x] = 255;
  13.         }
  14. }

  1. //使用双循环的方式 将图像image赋值为白色
  2. void setAllWhite(Mat& image)
  3. {
  4.         int x,y;

  5.         //计算图像一行需要被赋值的个数
  6.         int rowLength = image.cols*image.channels();

  7.         for(y=0;y<image.rows;y++)
  8.         {
  9.                 //获取第行的起始地址
  10.                 uchar* data  = image.ptr<uchar>(y);

  11.                 //对第y行逐个赋值
  12.                 for(x=0;x<rowLength;x++)
  13.                 {
  14.                         *data++=255;
  15.                 }
  16.         }
  17. }

比较不同方法的用时,可以参考下面的代码
  1. //比较 两种方法的运行速度
  2. void compareTime(Mat& image)
  3. {
  4.         int count = 100000;
  5.         long begin,end;

  6.         //统计双循环方式运行count次需要的时间
  7.         begin = clock();
  8.         while(count-->0)
  9.                 setAllWhite(image);
  10.         end = clock();

  11.         //输出时间
  12.         printf("time is %f \n",(double)(end-begin)/(double)CLOCKS_PER_SEC);

  13.         //统计单循环方式运行count次需要的时间
  14.         count = 100000;
  15.         begin = clock();
  16.         while(count-->0)
  17.                 setAllWhiteE(image);
  18.         end = clock();

  19.         //输出时间
  20.         printf("time is %f \n",(double)(end-begin)/(double)CLOCKS_PER_SEC);


  21. }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值