c++遍历图像三种方式以及耗时比较

  1. 指针方式
  2. at方式
  3. 迭代器方式
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>

using namespace std;
using namespace cv;

void ptr_cost(Mat img) {

	for (int i = 0; i < img.rows; ++i)
	{
		Vec3b* p =img.ptr<Vec3b>(i);
		for (int j = 0; j < img.cols; ++j)
		{
			p[j][0] = i % 255;      //Blue
			p[j][1] = j % 255;      //Gree
			p[j][2] = 0;            //Red
		}
	}

}

void iterate_cost(Mat img) {
	MatIterator_<Vec3b> colorit, colorend;
	for (colorit =img.begin<Vec3b>(), colorend = img.end<Vec3b>(); colorit != colorend; ++colorit)
	{
		(*colorit)[0] = rand() % 255;       //Blue
		(*colorit)[1] = rand() % 255;       //Green
		(*colorit)[2] = rand() % 255;       //Red
	}
}
void  at_cost(Mat img) {
	for (int i = 0; i < img.rows; ++i)         //遍历行
		for (int j = 0; j < img.cols; ++j)     //遍历列
		{
			Vec3b pixel;            //定义三通道像素值变量
			pixel[0] = i % 255;     //Blue
			pixel[1] = j % 255;     //Green
			pixel[2] = 0;           //Red

			img.at<Vec3b>(i, j) = pixel;
		}
	
}


int main()
{
	Mat image = cv::imread("./002.jpg");

	double ptrtimeConsume = static_cast<double>(getTickCount());
	ptr_cost(image);
	ptrtimeConsume = ((double)getTickCount() - ptrtimeConsume) / getTickFrequency();
	cout << "ptr_cost: " << ptrtimeConsume << endl;

	double attimeConsume = static_cast<double>(getTickCount());
	at_cost(image);
	attimeConsume = ((double)getTickCount() - attimeConsume) / getTickFrequency();
	cout << "at_cost: " << attimeConsume << endl;

	double itertimeConsume = static_cast<double>(getTickCount());
	iterate_cost(image);
	itertimeConsume = ((double)getTickCount() - itertimeConsume) / getTickFrequency();
	cout << "iterate_cost: " << itertimeConsume << endl;


	namedWindow("Image", WINDOW_AUTOSIZE);
	imshow("Image", image);

	waitKey(0);

	return 0;
}

 

测试图片 

耗时打印

小结:

1、工程化时建议使用指针方式遍历图像。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值