Update the trunk to the OpenCV's CVS (2008-07-14)
[opencv] / samples / c / squares.c
1 //
2 // The full "Square Detector" program.
3 // It loads several images subsequentally and tries to find squares in
4 // each image
5 //
6 #ifdef _CH_
7 #pragma package <opencv>
8 #endif
9
10 #include "cv.h"
11 #include "highgui.h"
12 #include <stdio.h>
13 #include <math.h>
14 #include <string.h>
15
16 int thresh = 50;
17 IplImage* img = 0;
18 IplImage* img0 = 0;
19 CvMemStorage* storage = 0;
20 const char* wndname = "Square Detection Demo";
21
22 // helper function:
23 // finds a cosine of angle between vectors
24 // from pt0->pt1 and from pt0->pt2 
25 double angle( CvPoint* pt1, CvPoint* pt2, CvPoint* pt0 )
26 {
27     double dx1 = pt1->x - pt0->x;
28     double dy1 = pt1->y - pt0->y;
29     double dx2 = pt2->x - pt0->x;
30     double dy2 = pt2->y - pt0->y;
31     return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
32 }
33
34 // returns sequence of squares detected on the image.
35 // the sequence is stored in the specified memory storage
36 CvSeq* findSquares4( IplImage* img, CvMemStorage* storage )
37 {
38     CvSeq* contours;
39     int i, c, l, N = 11;
40     CvSize sz = cvSize( img->width & -2, img->height & -2 );
41     IplImage* timg = cvCloneImage( img ); // make a copy of input image
42     IplImage* gray = cvCreateImage( sz, 8, 1 ); 
43     IplImage* pyr = cvCreateImage( cvSize(sz.width/2, sz.height/2), 8, 3 );
44     IplImage* tgray;
45     CvSeq* result;
46     double s, t;
47     // create empty sequence that will contain points -
48     // 4 points per square (the square's vertices)
49     CvSeq* squares = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvPoint), storage );
50     
51     // select the maximum ROI in the image
52     // with the width and height divisible by 2
53     cvSetImageROI( timg, cvRect( 0, 0, sz.width, sz.height ));
54     
55     // down-scale and upscale the image to filter out the noise
56     cvPyrDown( timg, pyr, 7 );
57     cvPyrUp( pyr, timg, 7 );
58     tgray = cvCreateImage( sz, 8, 1 );
59     
60     // find squares in every color plane of the image
61     for( c = 0; c < 3; c++ )
62     {
63         // extract the c-th color plane
64         cvSetImageCOI( timg, c+1 );
65         cvCopy( timg, tgray, 0 );
66         
67         // try several threshold levels
68         for( l = 0; l < N; l++ )
69         {
70             // hack: use Canny instead of zero threshold level.
71             // Canny helps to catch squares with gradient shading   
72             if( l == 0 )
73             {
74                 // apply Canny. Take the upper threshold from slider
75                 // and set the lower to 0 (which forces edges merging) 
76                 cvCanny( tgray, gray, 0, thresh, 5 );
77                 // dilate canny output to remove potential
78                 // holes between edge segments 
79                 cvDilate( gray, gray, 0, 1 );
80             }
81             else
82             {
83                 // apply threshold if l!=0:
84                 //     tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
85                 cvThreshold( tgray, gray, (l+1)*255/N, 255, CV_THRESH_BINARY );
86             }
87             
88             // find contours and store them all as a list
89             cvFindContours( gray, storage, &contours, sizeof(CvContour),
90                 CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) );
91             
92             // test each contour
93             while( contours )
94             {
95                 // approximate contour with accuracy proportional
96                 // to the contour perimeter
97                 result = cvApproxPoly( contours, sizeof(CvContour), storage,
98                     CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0 );
99                 // square contours should have 4 vertices after approximation
100                 // relatively large area (to filter out noisy contours)
101                 // and be convex.
102                 // Note: absolute value of an area is used because
103                 // area may be positive or negative - in accordance with the
104                 // contour orientation
105                 if( result->total == 4 &&
106                     fabs(cvContourArea(result,CV_WHOLE_SEQ)) > 1000 &&
107                     cvCheckContourConvexity(result) )
108                 {
109                     s = 0;
110                     
111                     for( i = 0; i < 5; i++ )
112                     {
113                         // find minimum angle between joint
114                         // edges (maximum of cosine)
115                         if( i >= 2 )
116                         {
117                             t = fabs(angle(
118                             (CvPoint*)cvGetSeqElem( result, i ),
119                             (CvPoint*)cvGetSeqElem( result, i-2 ),
120                             (CvPoint*)cvGetSeqElem( result, i-1 )));
121                             s = s > t ? s : t;
122                         }
123                     }
124                     
125                     // if cosines of all angles are small
126                     // (all angles are ~90 degree) then write quandrange
127                     // vertices to resultant sequence 
128                     if( s < 0.3 )
129                         for( i = 0; i < 4; i++ )
130                             cvSeqPush( squares,
131                                 (CvPoint*)cvGetSeqElem( result, i ));
132                 }
133                 
134                 // take the next contour
135                 contours = contours->h_next;
136             }
137         }
138     }
139     
140     // release all the temporary images
141     cvReleaseImage( &gray );
142     cvReleaseImage( &pyr );
143     cvReleaseImage( &tgray );
144     cvReleaseImage( &timg );
145     
146     return squares;
147 }
148
149
150 // the function draws all the squares in the image
151 void drawSquares( IplImage* img, CvSeq* squares )
152 {
153     CvSeqReader reader;
154     IplImage* cpy = cvCloneImage( img );
155     int i;
156     
157     // initialize reader of the sequence
158     cvStartReadSeq( squares, &reader, 0 );
159     
160     // read 4 sequence elements at a time (all vertices of a square)
161     for( i = 0; i < squares->total; i += 4 )
162     {
163         CvPoint pt[4], *rect = pt;
164         int count = 4;
165         
166         // read 4 vertices
167         CV_READ_SEQ_ELEM( pt[0], reader );
168         CV_READ_SEQ_ELEM( pt[1], reader );
169         CV_READ_SEQ_ELEM( pt[2], reader );
170         CV_READ_SEQ_ELEM( pt[3], reader );
171         
172         // draw the square as a closed polyline 
173         cvPolyLine( cpy, &rect, &count, 1, 1, CV_RGB(0,255,0), 3, CV_AA, 0 );
174     }
175     
176     // show the resultant image
177     cvShowImage( wndname, cpy );
178     cvReleaseImage( &cpy );
179 }
180
181
182 char* names[] = { "pic1.png", "pic2.png", "pic3.png",
183                   "pic4.png", "pic5.png", "pic6.png", 0 };
184
185 int main(int argc, char** argv)
186 {
187     int i, c;
188     // create memory storage that will contain all the dynamic data
189     storage = cvCreateMemStorage(0);
190
191     for( i = 0; names[i] != 0; i++ )
192     {
193         // load i-th image
194         img0 = cvLoadImage( names[i], 1 );
195         if( !img0 )
196         {
197             printf("Couldn't load %s\n", names[i] );
198             continue;
199         }
200         img = cvCloneImage( img0 );
201         
202         // create window and a trackbar (slider) with parent "image" and set callback
203         // (the slider regulates upper threshold, passed to Canny edge detector) 
204         cvNamedWindow( wndname, 1 );
205         
206         // find and draw the squares
207         drawSquares( img, findSquares4( img, storage ) );
208         
209         // wait for key.
210         // Also the function cvWaitKey takes care of event processing
211         c = cvWaitKey(0);
212         // release both images
213         cvReleaseImage( &img );
214         cvReleaseImage( &img0 );
215         // clear memory storage - reset free space position
216         cvClearMemStorage( storage );
217         if( (char)c == 27 )
218             break;
219     }
220     
221     cvDestroyWindow( wndname );
222     
223     return 0;
224 }