Merge pull request #1263 from abidrahmank:pyCLAHE_24
[profile/ivi/opencv.git] / samples / ocl / squares.cpp
1 // The "Square Detector" program.
2 // It loads several images sequentially and tries to find squares in
3 // each image
4
5 #include "opencv2/core/core.hpp"
6 #include "opencv2/imgproc/imgproc.hpp"
7 #include "opencv2/highgui/highgui.hpp"
8 #include "opencv2/ocl/ocl.hpp"
9 #include <iostream>
10 #include <math.h>
11 #include <string.h>
12
13 using namespace cv;
14 using namespace std;
15
16 #define ACCURACY_CHECK 1
17
18 #if ACCURACY_CHECK
19 // check if two vectors of vector of points are near or not
20 // prior assumption is that they are in correct order
21 static bool checkPoints(
22     vector< vector<Point> > set1,
23     vector< vector<Point> > set2,
24     int maxDiff = 5)
25 {
26     if(set1.size() != set2.size())
27     {
28         return false;
29     }
30
31     for(vector< vector<Point> >::iterator it1 = set1.begin(), it2 = set2.begin();
32             it1 < set1.end() && it2 < set2.end(); it1 ++, it2 ++)
33     {
34         vector<Point> pts1 = *it1;
35         vector<Point> pts2 = *it2;
36
37
38         if(pts1.size() != pts2.size())
39         {
40             return false;
41         }
42         for(size_t i = 0; i < pts1.size(); i ++)
43         {
44             Point pt1 = pts1[i], pt2 = pts2[i];
45             if(std::abs(pt1.x - pt2.x) > maxDiff ||
46                     std::abs(pt1.y - pt2.y) > maxDiff)
47             {
48                 return false;
49             }
50         }
51     }
52     return true;
53 }
54 #endif
55
56 int thresh = 50, N = 11;
57 const char* wndname = "OpenCL Square Detection Demo";
58
59
60 // helper function:
61 // finds a cosine of angle between vectors
62 // from pt0->pt1 and from pt0->pt2
63 static double angle( Point pt1, Point pt2, Point pt0 )
64 {
65     double dx1 = pt1.x - pt0.x;
66     double dy1 = pt1.y - pt0.y;
67     double dx2 = pt2.x - pt0.x;
68     double dy2 = pt2.y - pt0.y;
69     return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
70 }
71
72
73 // returns sequence of squares detected on the image.
74 // the sequence is stored in the specified memory storage
75 static void findSquares( const Mat& image, vector<vector<Point> >& squares )
76 {
77     squares.clear();
78     Mat pyr, timg, gray0(image.size(), CV_8U), gray;
79
80     // down-scale and upscale the image to filter out the noise
81     pyrDown(image, pyr, Size(image.cols/2, image.rows/2));
82     pyrUp(pyr, timg, image.size());
83     vector<vector<Point> > contours;
84
85     // find squares in every color plane of the image
86     for( int c = 0; c < 3; c++ )
87     {
88         int ch[] = {c, 0};
89         mixChannels(&timg, 1, &gray0, 1, ch, 1);
90
91         // try several threshold levels
92         for( int l = 0; l < N; l++ )
93         {
94             // hack: use Canny instead of zero threshold level.
95             // Canny helps to catch squares with gradient shading
96             if( l == 0 )
97             {
98                 // apply Canny. Take the upper threshold from slider
99                 // and set the lower to 0 (which forces edges merging)
100                 Canny(gray0, gray, 0, thresh, 5);
101                 // dilate canny output to remove potential
102                 // holes between edge segments
103                 dilate(gray, gray, Mat(), Point(-1,-1));
104             }
105             else
106             {
107                 // apply threshold if l!=0:
108                 //     tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
109                 cv::threshold(gray0, gray, (l+1)*255/N, 255, THRESH_BINARY);
110             }
111
112             // find contours and store them all as a list
113             findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
114
115             vector<Point> approx;
116
117             // test each contour
118             for( size_t i = 0; i < contours.size(); i++ )
119             {
120                 // approximate contour with accuracy proportional
121                 // to the contour perimeter
122                 approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);
123
124                 // square contours should have 4 vertices after approximation
125                 // relatively large area (to filter out noisy contours)
126                 // and be convex.
127                 // Note: absolute value of an area is used because
128                 // area may be positive or negative - in accordance with the
129                 // contour orientation
130                 if( approx.size() == 4 &&
131                         fabs(contourArea(Mat(approx))) > 1000 &&
132                         isContourConvex(Mat(approx)) )
133                 {
134                     double maxCosine = 0;
135
136                     for( int j = 2; j < 5; j++ )
137                     {
138                         // find the maximum cosine of the angle between joint edges
139                         double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
140                         maxCosine = MAX(maxCosine, cosine);
141                     }
142
143                     // if cosines of all angles are small
144                     // (all angles are ~90 degree) then write quandrange
145                     // vertices to resultant sequence
146                     if( maxCosine < 0.3 )
147                         squares.push_back(approx);
148                 }
149             }
150         }
151     }
152 }
153
154
155 // returns sequence of squares detected on the image.
156 // the sequence is stored in the specified memory storage
157 static void findSquares_ocl( const Mat& image, vector<vector<Point> >& squares )
158 {
159     squares.clear();
160
161     Mat gray;
162     cv::ocl::oclMat pyr_ocl, timg_ocl, gray0_ocl, gray_ocl;
163
164     // down-scale and upscale the image to filter out the noise
165     ocl::pyrDown(ocl::oclMat(image), pyr_ocl);
166     ocl::pyrUp(pyr_ocl, timg_ocl);
167
168     vector<vector<Point> > contours;
169     vector<cv::ocl::oclMat> gray0s;
170     ocl::split(timg_ocl, gray0s); // split 3 channels into a vector of oclMat
171     // find squares in every color plane of the image
172     for( int c = 0; c < 3; c++ )
173     {
174         gray0_ocl = gray0s[c];
175         // try several threshold levels
176         for( int l = 0; l < N; l++ )
177         {
178             // hack: use Canny instead of zero threshold level.
179             // Canny helps to catch squares with gradient shading
180             if( l == 0 )
181             {
182                 // do canny on OpenCL device
183                 // apply Canny. Take the upper threshold from slider
184                 // and set the lower to 0 (which forces edges merging)
185                 cv::ocl::Canny(gray0_ocl, gray_ocl, 0, thresh, 5);
186                 // dilate canny output to remove potential
187                 // holes between edge segments
188                 ocl::dilate(gray_ocl, gray_ocl, Mat(), Point(-1,-1));
189                 gray = Mat(gray_ocl);
190             }
191             else
192             {
193                 // apply threshold if l!=0:
194                 //     tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
195                 cv::ocl::threshold(gray0_ocl, gray_ocl, (l+1)*255/N, 255, THRESH_BINARY);
196                 gray = gray_ocl;
197             }
198
199             // find contours and store them all as a list
200             findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
201
202             vector<Point> approx;
203             // test each contour
204             for( size_t i = 0; i < contours.size(); i++ )
205             {
206                 // approximate contour with accuracy proportional
207                 // to the contour perimeter
208                 approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);
209
210                 // square contours should have 4 vertices after approximation
211                 // relatively large area (to filter out noisy contours)
212                 // and be convex.
213                 // Note: absolute value of an area is used because
214                 // area may be positive or negative - in accordance with the
215                 // contour orientation
216                 if( approx.size() == 4 &&
217                         fabs(contourArea(Mat(approx))) > 1000 &&
218                         isContourConvex(Mat(approx)) )
219                 {
220                     double maxCosine = 0;
221                     for( int j = 2; j < 5; j++ )
222                     {
223                         // find the maximum cosine of the angle between joint edges
224                         double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
225                         maxCosine = MAX(maxCosine, cosine);
226                     }
227
228                     // if cosines of all angles are small
229                     // (all angles are ~90 degree) then write quandrange
230                     // vertices to resultant sequence
231                     if( maxCosine < 0.3 )
232                         squares.push_back(approx);
233                 }
234             }
235         }
236     }
237 }
238
239
240 // the function draws all the squares in the image
241 static void drawSquares( Mat& image, const vector<vector<Point> >& squares )
242 {
243     for( size_t i = 0; i < squares.size(); i++ )
244     {
245         const Point* p = &squares[i][0];
246         int n = (int)squares[i].size();
247         polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, CV_AA);
248     }
249 }
250
251
252 // draw both pure-C++ and ocl square results onto a single image
253 static Mat drawSquaresBoth( const Mat& image,
254                             const vector<vector<Point> >& sqsCPP,
255                             const vector<vector<Point> >& sqsOCL
256 )
257 {
258     Mat imgToShow(Size(image.cols * 2, image.rows), image.type());
259     Mat lImg = imgToShow(Rect(Point(0, 0), image.size()));
260     Mat rImg = imgToShow(Rect(Point(image.cols, 0), image.size()));
261     image.copyTo(lImg);
262     image.copyTo(rImg);
263     drawSquares(lImg, sqsCPP);
264     drawSquares(rImg, sqsOCL);
265     float fontScale = 0.8f;
266     Scalar white = Scalar::all(255), black = Scalar::all(0);
267
268     putText(lImg, "C++", Point(10, 20), FONT_HERSHEY_COMPLEX_SMALL, fontScale, black, 2);
269     putText(rImg, "OCL", Point(10, 20), FONT_HERSHEY_COMPLEX_SMALL, fontScale, black, 2);
270     putText(lImg, "C++", Point(10, 20), FONT_HERSHEY_COMPLEX_SMALL, fontScale, white, 1);
271     putText(rImg, "OCL", Point(10, 20), FONT_HERSHEY_COMPLEX_SMALL, fontScale, white, 1);
272
273     return imgToShow;
274 }
275
276
277 int main(int argc, char** argv)
278 {
279     const char* keys =
280         "{ i | input   |                    | specify input image }"
281         "{ o | output  | squares_output.jpg | specify output save path}";
282     CommandLineParser cmd(argc, argv, keys);
283     string inputName = cmd.get<string>("i");
284     string outfile = cmd.get<string>("o");
285     if(inputName.empty())
286     {
287         cout << "Avaible options:" << endl;
288         cmd.printParams();
289         return 0;
290     }
291
292     vector<ocl::Info> info;
293     CV_Assert(ocl::getDevice(info));
294     int iterations = 10;
295     namedWindow( wndname, 1 );
296     vector<vector<Point> > squares_cpu, squares_ocl;
297
298     Mat image = imread(inputName, 1);
299     if( image.empty() )
300     {
301         cout << "Couldn't load " << inputName << endl;
302         return -1;
303     }
304     int j = iterations;
305     int64 t_ocl = 0, t_cpp = 0;
306     //warm-ups
307     cout << "warming up ..." << endl;
308     findSquares(image, squares_cpu);
309     findSquares_ocl(image, squares_ocl);
310
311
312 #if ACCURACY_CHECK
313     cout << "Checking ocl accuracy ... " << endl;
314     cout << (checkPoints(squares_cpu, squares_ocl) ? "Pass" : "Failed") << endl;
315 #endif
316     do
317     {
318         int64 t_start = cv::getTickCount();
319         findSquares(image, squares_cpu);
320         t_cpp += cv::getTickCount() - t_start;
321
322
323         t_start  = cv::getTickCount();
324         findSquares_ocl(image, squares_ocl);
325         t_ocl += cv::getTickCount() - t_start;
326         cout << "run loop: " << j << endl;
327     }
328     while(--j);
329     cout << "cpp average time: " << 1000.0f * (double)t_cpp / getTickFrequency() / iterations << "ms" << endl;
330     cout << "ocl average time: " << 1000.0f * (double)t_ocl / getTickFrequency() / iterations << "ms" << endl;
331
332     Mat result = drawSquaresBoth(image, squares_cpu, squares_ocl);
333     imshow(wndname, result);
334     imwrite(outfile, result);
335     cvWaitKey(0);
336
337     return 0;
338 }