2 // The full "Square Detector" program.
3 // It loads several images subsequentally and tries to find squares in
6 #include "opencv2/imgproc/imgproc_c.h"
7 #include "opencv2/highgui/highgui.hpp"
15 CvMemStorage* storage = 0;
16 const char* wndname = "Square Detection Demo";
19 // finds a cosine of angle between vectors
20 // from pt0->pt1 and from pt0->pt2
21 double angle( CvPoint* pt1, CvPoint* pt2, CvPoint* pt0 )
23 double dx1 = pt1->x - pt0->x;
24 double dy1 = pt1->y - pt0->y;
25 double dx2 = pt2->x - pt0->x;
26 double dy2 = pt2->y - pt0->y;
27 return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
30 // returns sequence of squares detected on the image.
31 // the sequence is stored in the specified memory storage
32 CvSeq* findSquares4( IplImage* img, CvMemStorage* storage )
36 CvSize sz = cvSize( img->width & -2, img->height & -2 );
37 IplImage* timg = cvCloneImage( img ); // make a copy of input image
38 IplImage* gray = cvCreateImage( sz, 8, 1 );
39 IplImage* pyr = cvCreateImage( cvSize(sz.width/2, sz.height/2), 8, 3 );
43 // create empty sequence that will contain points -
44 // 4 points per square (the square's vertices)
45 CvSeq* squares = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvPoint), storage );
46 // select the maximum ROI in the image
47 // with the width and height divisible by 2
48 cvSetImageROI( timg, cvRect( 0, 0, sz.width, sz.height ));
50 // down-scale and upscale the image to filter out the noise
51 cvPyrDown( timg, pyr, 7 );
52 cvPyrUp( pyr, timg, 7 );
53 tgray = cvCreateImage( sz, 8, 1 );
55 // find squares in every color plane of the image
56 for( c = 0; c < 3; c++ )
58 // extract the c-th color plane
59 cvSetImageCOI( timg, c+1 );
60 cvCopy( timg, tgray, 0 );
62 // try several threshold levels
63 for( l = 0; l < N; l++ )
65 // hack: use Canny instead of zero threshold level.
66 // Canny helps to catch squares with gradient shading
69 // apply Canny. Take the upper threshold from slider
70 // and set the lower to 0 (which forces edges merging)
71 cvCanny( tgray, gray, 0, thresh, 5 );
72 // dilate canny output to remove potential
73 // holes between edge segments
74 cvDilate( gray, gray, 0, 1 );
78 // apply threshold if l!=0:
79 // tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
80 cvThreshold( tgray, gray, (l+1)*255/N, 255, CV_THRESH_BINARY );
83 // find contours and store them all as a list
84 cvFindContours( gray, storage, &contours, sizeof(CvContour),
85 CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) );
90 // approximate contour with accuracy proportional
91 // to the contour perimeter
92 result = cvApproxPoly( contours, sizeof(CvContour), storage,
93 CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0 );
94 // square contours should have 4 vertices after approximation
95 // relatively large area (to filter out noisy contours)
97 // Note: absolute value of an area is used because
98 // area may be positive or negative - in accordance with the
99 // contour orientation
100 if( result->total == 4 &&
101 cvContourArea(result,CV_WHOLE_SEQ,0) > 1000 &&
102 cvCheckContourConvexity(result) )
106 for( i = 0; i < 5; i++ )
108 // find minimum angle between joint
109 // edges (maximum of cosine)
113 (CvPoint*)cvGetSeqElem( result, i ),
114 (CvPoint*)cvGetSeqElem( result, i-2 ),
115 (CvPoint*)cvGetSeqElem( result, i-1 )));
120 // if cosines of all angles are small
121 // (all angles are ~90 degree) then write quandrange
122 // vertices to resultant sequence
124 for( i = 0; i < 4; i++ )
126 (CvPoint*)cvGetSeqElem( result, i ));
129 // take the next contour
130 contours = contours->h_next;
135 // release all the temporary images
136 cvReleaseImage( &gray );
137 cvReleaseImage( &pyr );
138 cvReleaseImage( &tgray );
139 cvReleaseImage( &timg );
145 // the function draws all the squares in the image
146 void drawSquares( IplImage* img, CvSeq* squares )
149 IplImage* cpy = cvCloneImage( img );
152 // initialize reader of the sequence
153 cvStartReadSeq( squares, &reader, 0 );
155 // read 4 sequence elements at a time (all vertices of a square)
156 for( i = 0; i < squares->total; i += 4 )
158 CvPoint pt[4], *rect = pt;
162 CV_READ_SEQ_ELEM( pt[0], reader );
163 CV_READ_SEQ_ELEM( pt[1], reader );
164 CV_READ_SEQ_ELEM( pt[2], reader );
165 CV_READ_SEQ_ELEM( pt[3], reader );
167 // draw the square as a closed polyline
168 cvPolyLine( cpy, &rect, &count, 1, 1, CV_RGB(0,255,0), 3, CV_AA, 0 );
171 // show the resultant image
172 cvShowImage( wndname, cpy );
173 cvReleaseImage( &cpy );
177 char* names[] = { "pic1.png", "pic2.png", "pic3.png",
178 "pic4.png", "pic5.png", "pic6.png", 0 };
180 int main(int argc, char** argv)
183 // create memory storage that will contain all the dynamic data
184 storage = cvCreateMemStorage(0);
186 for( i = 0; names[i] != 0; i++ )
189 img0 = cvLoadImage( names[i], 1 );
192 printf("Couldn't load %s\n", names[i] );
195 img = cvCloneImage( img0 );
197 // create window and a trackbar (slider) with parent "image" and set callback
198 // (the slider regulates upper threshold, passed to Canny edge detector)
199 cvNamedWindow( wndname, 1 );
201 // find and draw the squares
202 drawSquares( img, findSquares4( img, storage ) );
205 // Also the function cvWaitKey takes care of event processing
207 // release both images
208 cvReleaseImage( &img );
209 cvReleaseImage( &img0 );
210 // clear memory storage - reset free space position
211 cvClearMemStorage( storage );
216 cvDestroyWindow( wndname );
218 cvReleaseMemStorage(&storage);