三种方法分别问:
指针访问: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 = 0; i < rowNumber; i++) { uchar* data = outputImage.ptr<uchar>(i); for (size_t j = 0; j < colNumber; j++) { data[j] = data[j] / div*div + div / 2; } } } 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 = 0; px < 3; px++) { (*it)[px] = (*it)[px] / div*div + div / 2; } } } 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 = 0; i < rowNumber; i++) { for (size_t j = 0; j < colNumber; j++) { for (size_t px = 0; px < 3; px++) { outputImage.at<cv::Vec3b>(i, j)[px] = outputImage.at<cv::Vec3b>(i, j)[px] / div * div + div / 2; } } } } 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, 32); timeStart = ((double)cv::getTickCount() - timeStart) / cv::getTickFrequency(); cout << "ptr方法运行时间为:" << timeStart << "秒" << endl; timeStart = static_cast<double>(cv::getTickCount()); colorReduce_iterator(srcImg, dstImg, 32); timeStart = ((double)cv::getTickCount() - timeStart) / cv::getTickFrequency(); cout << "iterator方法运行时间为:" << timeStart << "秒" << endl; timeStart = static_cast<double>(cv::getTickCount()); colorReduce_at(srcImg, dstImg, 32); timeStart = ((double)cv::getTickCount() - timeStart) / cv::getTickFrequency(); cout << "at方法运行时间为:" << timeStart << "秒" << endl; cv::imshow("dstImg", dstImg); cv::waitKey(0); }