三种方法分别问:
指针访问:void colorReduce_ptr(cv::Mat &inputImage, cv::Mat &outputImage, int div);
迭代器访问:void colorReduce_iterator(cv::Mat &inputImage, cv::Mat &outputImage, int div);
动态地址计算:void colorReduce_at(cv::Mat &inputImage, cv::Mat &outputImage, int div);
#include <opencv.hpp>
#include <iostream> using namespace std; void colorReduce_ptr(cv::Mat &inputImage, cv::Mat &outputImage, int div);
void colorReduce_iterator(cv::Mat &inputImage, cv::Mat &outputImage, int div);
void colorReduce_at(cv::Mat &inputImage, cv::Mat &outputImage, int div); void colorReduce_ptr(cv::Mat &inputImage, cv::Mat &outputImage, int div)
{
outputImage = inputImage.clone();
int rowNumber = outputImage.rows;
int colNumber = outputImage.cols*outputImage.channels();
for (size_t i = ; i < rowNumber; i++)
{
uchar* data = outputImage.ptr<uchar>(i);
for (size_t j = ; j < colNumber; j++)
{
data[j] = data[j] / div*div + div / ;
}
}
} void colorReduce_iterator(cv::Mat &inputImage, cv::Mat &outputImage, int div)
{
outputImage = inputImage.clone();
cv::Mat_<cv::Vec3b>::iterator it = outputImage.begin<cv::Vec3b>();
cv::Mat_<cv::Vec3b>::iterator it_end = outputImage.end<cv::Vec3b>(); for (;it != it_end; ++it)
{
for (size_t px = ; px < ; px++)
{
(*it)[px] = (*it)[px] / div*div + div / ;
}
}
} void colorReduce_at(cv::Mat &inputImage, cv::Mat &outputImage, int div)
{
outputImage = inputImage.clone();
int rowNumber = outputImage.rows;
int colNumber = outputImage.cols; for (size_t i = ; i < rowNumber; i++)
{
for (size_t j = ; j < colNumber; j++)
{
for (size_t px = ; px < ; px++)
{
outputImage.at<cv::Vec3b>(i, j)[px] = outputImage.at<cv::Vec3b>(i, j)[px] / div * div + div / ;
}
}
}
} int main(int argc, char** argv[])
{
cv::Mat srcImg = cv::imread("E:/data/lena.jpg");
cv::imshow("srcImg", srcImg); cv::Mat dstImg;
dstImg.create(srcImg.rows, srcImg.cols, srcImg.type()); double timeStart;
timeStart = static_cast<double>(cv::getTickCount());
colorReduce_ptr(srcImg, dstImg, );
timeStart = ((double)cv::getTickCount() - timeStart) / cv::getTickFrequency();
cout << "ptr方法运行时间为:" << timeStart << "秒" << endl; timeStart = static_cast<double>(cv::getTickCount());
colorReduce_iterator(srcImg, dstImg, );
timeStart = ((double)cv::getTickCount() - timeStart) / cv::getTickFrequency();
cout << "iterator方法运行时间为:" << timeStart << "秒" << endl; timeStart = static_cast<double>(cv::getTickCount());
colorReduce_at(srcImg, dstImg, );
timeStart = ((double)cv::getTickCount() - timeStart) / cv::getTickFrequency();
cout << "at方法运行时间为:" << timeStart << "秒" << endl; cv::imshow("dstImg", dstImg);
cv::waitKey();
}