1 // The "Square Detector" program.
2 // It loads several images sequentially and tries to find squares in
5 #include "opencv2/core/core.hpp"
6 #include "opencv2/imgproc/imgproc.hpp"
7 #include "opencv2/highgui/highgui.hpp"
8 #include "opencv2/ocl/ocl.hpp"
16 #define ACCURACY_CHECK 1
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,
26 if(set1.size() != set2.size())
31 for(vector< vector<Point> >::iterator it1 = set1.begin(), it2 = set2.begin();
32 it1 < set1.end() && it2 < set2.end(); it1 ++, it2 ++)
34 vector<Point> pts1 = *it1;
35 vector<Point> pts2 = *it2;
38 if(pts1.size() != pts2.size())
42 for(size_t i = 0; i < pts1.size(); i ++)
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)
56 int thresh = 50, N = 11;
57 const char* wndname = "OpenCL Square Detection Demo";
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 )
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);
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 )
78 Mat pyr, timg, gray0(image.size(), CV_8U), gray;
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;
85 // find squares in every color plane of the image
86 for( int c = 0; c < 3; c++ )
89 mixChannels(&timg, 1, &gray0, 1, ch, 1);
91 // try several threshold levels
92 for( int l = 0; l < N; l++ )
94 // hack: use Canny instead of zero threshold level.
95 // Canny helps to catch squares with gradient shading
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));
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);
112 // find contours and store them all as a list
113 findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
115 vector<Point> approx;
118 for( size_t i = 0; i < contours.size(); i++ )
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);
124 // square contours should have 4 vertices after approximation
125 // relatively large area (to filter out noisy contours)
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)) )
134 double maxCosine = 0;
136 for( int j = 2; j < 5; j++ )
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);
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);
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 )
162 cv::ocl::oclMat pyr_ocl, timg_ocl, gray0_ocl, gray_ocl;
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);
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++ )
174 gray0_ocl = gray0s[c];
175 // try several threshold levels
176 for( int l = 0; l < N; l++ )
178 // hack: use Canny instead of zero threshold level.
179 // Canny helps to catch squares with gradient shading
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);
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);
199 // find contours and store them all as a list
200 findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
202 vector<Point> approx;
204 for( size_t i = 0; i < contours.size(); i++ )
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);
210 // square contours should have 4 vertices after approximation
211 // relatively large area (to filter out noisy contours)
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)) )
220 double maxCosine = 0;
221 for( int j = 2; j < 5; j++ )
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);
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);
240 // the function draws all the squares in the image
241 static void drawSquares( Mat& image, const vector<vector<Point> >& squares )
243 for( size_t i = 0; i < squares.size(); i++ )
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);
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
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()));
263 drawSquares(lImg, sqsCPP);
264 drawSquares(rImg, sqsOCL);
265 float fontScale = 0.8f;
266 Scalar white = Scalar::all(255), black = Scalar::all(0);
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);
277 int main(int argc, char** argv)
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())
287 cout << "Avaible options:" << endl;
292 vector<ocl::Info> info;
293 CV_Assert(ocl::getDevice(info));
295 namedWindow( wndname, 1 );
296 vector<vector<Point> > squares_cpu, squares_ocl;
298 Mat image = imread(inputName, 1);
301 cout << "Couldn't load " << inputName << endl;
305 int64 t_ocl = 0, t_cpp = 0;
307 cout << "warming up ..." << endl;
308 findSquares(image, squares_cpu);
309 findSquares_ocl(image, squares_ocl);
313 cout << "Checking ocl accuracy ... " << endl;
314 cout << (checkPoints(squares_cpu, squares_ocl) ? "Pass" : "Failed") << endl;
318 int64 t_start = cv::getTickCount();
319 findSquares(image, squares_cpu);
320 t_cpp += cv::getTickCount() - t_start;
323 t_start = cv::getTickCount();
324 findSquares_ocl(image, squares_ocl);
325 t_ocl += cv::getTickCount() - t_start;
326 cout << "run loop: " << j << endl;
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;
332 Mat result = drawSquaresBoth(image, squares_cpu, squares_ocl);
333 imshow(wndname, result);
334 imwrite(outfile, result);