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