openCV2使用指针的方式遍历图像image.ptr

#include "opencv2/opencv.hpp"

#include <time.h>

using namespace cv;
using namespace std;

//使用单循环的方式 将图像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);


}

int main(int argc, char* argv[])
{
        

        //读取图像 本图像可以在opencv的安装目录下 samples/c中找到
        Mat src;
        src = imread("lena.jpg");

        
        //比较两种不同方法的效率
        compareTime(src);

        //显示图像
        namedWindow("src");
        imshow("src",src);
        waitKey(0);

        //创建一个isContinuous() 返回false的矩阵
        uchar data[100];
        Mat dst(10,10,CV_8U,(void*)data,12);
        //dst.isContinuous()

        return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值