首页 > 代码库 > 读取图像,LUT以及计算耗时

读取图像,LUT以及计算耗时

使用LUT(lookup table)检索表的方法,提高color reduce时对像素读取的速度。

实现对Mat对象中数据的读取,并计算color reduce的速度。

 1 #include <opencv2/core/core.hpp>
 2 #include <opencv2/highgui/highgui.hpp>
 3 #include <iostream>
 4 #include <sstream>
 5 
 6 using namespace std;
 7 using namespace cv;
 8 
 9 static void help(){
10   cout
11   << "Author: BJTShang" << endl
12   << "2016-12-22, CityU" << endl
13   << "Use: " << "./1222_LUP imageName divideWith [G]" << endl
14   <<endl;
15 }
16 
17 Mat& ScanImageAndReduceC(Mat& I, const uchar* table);
18 
19 int main(int argc, char** argv){
20   help();
21   if(argc<3){
22     cout << "Not enough parameters!" << endl;
23     return -1;
24   }
25   
26   Mat I;
27   char* imageName = argv[1];
28   if(argc==4 && !strcmp(argv[3],"G")){
29     I = imread(imageName, CV_LOAD_IMAGE_GRAYSCALE);
30   }else{
31     I = imread(imageName, CV_LOAD_IMAGE_COLOR);
32   } 
33   
34   if(!I.data){
35     cout << "The image" << imageName << " has no data!";
36     return -1;
37   }
38 
39   int divideWith = 0;
40   stringstream s;
41   s << argv[2];
42   s >> divideWith;
43   if(!s || !divideWith){
44     cout << "Invalid divideWith, input again (positive integer)!" << endl;
45     return -1;
46   }
47   
48   // use this table to search for (by simple assignment) reduced intensity, 
49   // instead of calculating for each pixel, which is computational high-cost
50   uchar table[256];
51   for(int i=0; i < 256; ++i){
52     table[i] = uchar((i/divideWith)*divideWith);
53   }
54   
55   int64 t0 = getTickCount();
56   Mat J = I.clone();
57   J = ScanImageAndReduceC(J, table);
58   double t = (double)(getTickCount() - t0)/getTickFrequency();
59   cout << "Elapse time = " << t*1000 << " ms" <<endl;
60   
61   namedWindow("before", CV_WINDOW_AUTOSIZE);
62   namedWindow("after color reduce by LUT", CV_WINDOW_AUTOSIZE);
63   imshow("before", I);
64   imshow("after color reduce by LUT", J);
65   waitKey(0);
66   return 0;
67 }
68 
69 Mat& ScanImageAndReduceC(Mat& I, const uchar* table){
70   CV_Assert(I.depth() == CV_8U);
71   const int channels = I.channels();
72   
73   int nRows = I.rows;
74   int nCols = I.cols*channels;
75   
76   if (I.isContinuous()){
77     nCols *= nRows;
78     nRows = 1;
79   }
80   
81   uchar* p = NULL;
82   for(size_t i=0; i<nRows; ++i){
83     p = I.ptr<uchar>(i);
84     for(size_t j=0; j<nCols; ++j){
85       p[j] = table[p[j]];
86     }
87   }
88   return I;
89 }

结果:

技术分享

 

读取图像,LUT以及计算耗时