#include "mainwindow.h" #include <QApplication> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; /* 名字: 顏色空間縮減函數 * 目的:減小圖像中顏色的數量 * 方法: 好比原來有256中顏色,要將其變成64種顏色: * 將原來的顏色/4而後乘以4就能夠了 */ /* 方法1:用指針訪問像素,release時速度最快 0.0066653 */ void colorReducePtr(Mat &inputImage, Mat& outputImage, int div) { //參數準備 outputImage = inputImage.clone(); //複製實參到臨時變量 int rowNumber = outputImage.rows; //行數 int colNumber = outputImage.cols * outputImage.channels(); //每一行元素的個數 = 類數 * 通道數 //雙for,遍歷全部像素值 for(int i = 0; i < rowNumber; ++i) //行 { uchar *data = outputImage.ptr<uchar>(i); //獲取第i行的首地址 for(int j = 0; j < colNumber; ++j) { data[j] = data[j]/div*div + div/2; // 處理每個像素 cout << data[j] << ends; } } } void colorReducePtr2(Mat &inputImage, Mat& outputImage, int div) { //參數準備 outputImage = inputImage.clone(); //複製實參到臨時變量 int rowNumber = outputImage.rows; //行數 int colNumber; if(outputImage.isContinuous()){ colNumber = outputImage.total() * outputImage.elemSize(); //每一行元素的個數 rowNumber = 1; uchar *data = outputImage.ptr<uchar>(0); //獲取第i行的首地址 for(int i = 0; i < colNumber; ++i){ data[i] = data[i]/div*div + div/2; } } } /* 0.242588 */ void colorReduceSTL(Mat &inputImage, Mat& outputImage, int div)//迭代器方式 { outputImage = inputImage.clone(); //複製實參到臨時變量 Mat_<Vec3b>::iterator it = outputImage.begin<Vec3b>(); Mat_<Vec3b>::iterator itEnd = outputImage.end<Vec3b>(); for(; it!=itEnd ; it++){ //處理每個像素 (*it)[0] = (*it)[0]/div *div + div/2; (*it)[1] = (*it)[1]/div *div + div/2; (*it)[2] = (*it)[2]/div *div + div/2; } } //At方式每每只用於隨機分爲某個位置上的像素值 void colorReduceAt(Mat& inputImage, Mat& outputImage, int div) { outputImage = inputImage.clone(); int rows = outputImage.rows; int cols = outputImage.cols; for(int i = 0;i < rows;i++) { for(int j = 0;j < cols;j++) { outputImage.at<Vec3b>(i,j)[0] = outputImage.at<Vec3b>(i,j)[0]/div*div + div/2; outputImage.at<Vec3b>(i,j)[1] = outputImage.at<Vec3b>(i,j)[1]/div*div + div/2; outputImage.at<Vec3b>(i,j)[2] = outputImage.at<Vec3b>(i,j)[2]/div*div + div/2; } } } int main(int argc, char *argv[]) { QApplication a(argc, argv); Mat srcImage = imread("F:\\MyCode\\dcq.jpg"); imshow("srcImage", srcImage); //按照原始圖的參數規格來建立效果圖 Mat dstImage ; dstImage.create(srcImage.rows, srcImage.cols, srcImage.type()); //記錄起始時間 double time0 = static_cast<double>(getTickCount()); //調用顏色空間縮減函數 colorReduceAt(srcImage, dstImage, 64); time0 = ((double)getTickCount() - time0) / getTickFrequency(); cout << "time: " << time0 << "[s]" << endl; //消耗的時間 imshow("dstImage", dstImage); return a.exec(); }