converted some more samples to C++
[profile/ivi/opencv.git] / 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 #include "opencv2/imgproc/imgproc_c.h"
7 #include "opencv2/highgui/highgui.hpp"
8 #include <stdio.h>
9 #include <math.h>
10 #include <string.h>
11
12 int thresh = 50;
13 IplImage* img = 0;
14 IplImage* img0 = 0;
15 CvMemStorage* storage = 0;
16 const char* wndname = "Square Detection Demo";
17
18 // helper function:
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 )
22 {
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);
28 }
29
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 )
33 {
34     CvSeq* contours;
35     int i, c, l, N = 11;
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 );
40     IplImage* tgray;
41     CvSeq* result;
42     double s, t;
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 ));
49
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 );
54
55     // find squares in every color plane of the image
56     for( c = 0; c < 3; c++ )
57     {
58         // extract the c-th color plane
59         cvSetImageCOI( timg, c+1 );
60         cvCopy( timg, tgray, 0 );
61
62         // try several threshold levels
63         for( l = 0; l < N; l++ )
64         {
65             // hack: use Canny instead of zero threshold level.
66             // Canny helps to catch squares with gradient shading
67             if( l == 0 )
68             {
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 );
75             }
76             else
77             {
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 );
81             }
82
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) );
86
87             // test each contour
88             while( contours )
89             {
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)
96                 // and be convex.
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) )
103                 {
104                     s = 0;
105
106                     for( i = 0; i < 5; i++ )
107                     {
108                         // find minimum angle between joint
109                         // edges (maximum of cosine)
110                         if( i >= 2 )
111                         {
112                             t = fabs(angle(
113                             (CvPoint*)cvGetSeqElem( result, i ),
114                             (CvPoint*)cvGetSeqElem( result, i-2 ),
115                             (CvPoint*)cvGetSeqElem( result, i-1 )));
116                             s = s > t ? s : t;
117                         }
118                     }
119
120                     // if cosines of all angles are small
121                     // (all angles are ~90 degree) then write quandrange
122                     // vertices to resultant sequence
123                     if( s < 0.3 )
124                         for( i = 0; i < 4; i++ )
125                             cvSeqPush( squares,
126                                 (CvPoint*)cvGetSeqElem( result, i ));
127                 }
128
129                 // take the next contour
130                 contours = contours->h_next;
131             }
132         }
133     }
134
135     // release all the temporary images
136     cvReleaseImage( &gray );
137     cvReleaseImage( &pyr );
138     cvReleaseImage( &tgray );
139     cvReleaseImage( &timg );
140
141     return squares;
142 }
143
144
145 // the function draws all the squares in the image
146 void drawSquares( IplImage* img, CvSeq* squares )
147 {
148     CvSeqReader reader;
149     IplImage* cpy = cvCloneImage( img );
150     int i;
151
152     // initialize reader of the sequence
153     cvStartReadSeq( squares, &reader, 0 );
154
155     // read 4 sequence elements at a time (all vertices of a square)
156     for( i = 0; i < squares->total; i += 4 )
157     {
158         CvPoint pt[4], *rect = pt;
159         int count = 4;
160
161         // read 4 vertices
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 );
166
167         // draw the square as a closed polyline
168         cvPolyLine( cpy, &rect, &count, 1, 1, CV_RGB(0,255,0), 3, CV_AA, 0 );
169     }
170
171     // show the resultant image
172     cvShowImage( wndname, cpy );
173     cvReleaseImage( &cpy );
174 }
175
176
177 char* names[] = { "pic1.png", "pic2.png", "pic3.png",
178                   "pic4.png", "pic5.png", "pic6.png", 0 };
179
180 int main(int argc, char** argv)
181 {
182     int i, c;
183     // create memory storage that will contain all the dynamic data
184     storage = cvCreateMemStorage(0);
185
186     for( i = 0; names[i] != 0; i++ )
187     {
188         // load i-th image
189         img0 = cvLoadImage( names[i], 1 );
190         if( !img0 )
191         {
192             printf("Couldn't load %s\n", names[i] );
193             continue;
194         }
195         img = cvCloneImage( img0 );
196
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 );
200
201         // find and draw the squares
202         drawSquares( img, findSquares4( img, storage ) );
203
204         // wait for key.
205         // Also the function cvWaitKey takes care of event processing
206         c = cvWaitKey(0);
207         // release both images
208         cvReleaseImage( &img );
209         cvReleaseImage( &img0 );
210         // clear memory storage - reset free space position
211         cvClearMemStorage( storage );
212         if( (char)c == 27 )
213             break;
214     }
215
216     cvDestroyWindow( wndname );
217     
218     cvReleaseMemStorage(&storage);
219
220     return 0;
221 }