2 // The full "Square Detector" program.
3 // It loads several images subsequentally and tries to find squares in
7 #pragma package <opencv>
10 #define CV_NO_BACKWARD_COMPATIBILITY
21 CvMemStorage* storage = 0;
22 const char* wndname = "Square Detection Demo";
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 )
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);
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 )
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 );
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 );
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 ));
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 );
62 // find squares in every color plane of the image
63 for( c = 0; c < 3; c++ )
65 // extract the c-th color plane
66 cvSetImageCOI( timg, c+1 );
67 cvCopy( timg, tgray, 0 );
69 // try several threshold levels
70 for( l = 0; l < N; l++ )
72 // hack: use Canny instead of zero threshold level.
73 // Canny helps to catch squares with gradient shading
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 );
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 );
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) );
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)
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) )
113 for( i = 0; i < 5; i++ )
115 // find minimum angle between joint
116 // edges (maximum of cosine)
120 (CvPoint*)cvGetSeqElem( result, i ),
121 (CvPoint*)cvGetSeqElem( result, i-2 ),
122 (CvPoint*)cvGetSeqElem( result, i-1 )));
127 // if cosines of all angles are small
128 // (all angles are ~90 degree) then write quandrange
129 // vertices to resultant sequence
131 for( i = 0; i < 4; i++ )
133 (CvPoint*)cvGetSeqElem( result, i ));
136 // take the next contour
137 contours = contours->h_next;
142 // release all the temporary images
143 cvReleaseImage( &gray );
144 cvReleaseImage( &pyr );
145 cvReleaseImage( &tgray );
146 cvReleaseImage( &timg );
152 // the function draws all the squares in the image
153 void drawSquares( IplImage* img, CvSeq* squares )
156 IplImage* cpy = cvCloneImage( img );
159 // initialize reader of the sequence
160 cvStartReadSeq( squares, &reader, 0 );
162 // read 4 sequence elements at a time (all vertices of a square)
163 for( i = 0; i < squares->total; i += 4 )
165 CvPoint pt[4], *rect = pt;
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 );
174 // draw the square as a closed polyline
175 cvPolyLine( cpy, &rect, &count, 1, 1, CV_RGB(0,255,0), 3, CV_AA, 0 );
178 // show the resultant image
179 cvShowImage( wndname, cpy );
180 cvReleaseImage( &cpy );
184 char* names[] = { "pic1.png", "pic2.png", "pic3.png",
185 "pic4.png", "pic5.png", "pic6.png", 0 };
187 int main(int argc, char** argv)
190 // create memory storage that will contain all the dynamic data
191 storage = cvCreateMemStorage(0);
193 for( i = 0; names[i] != 0; i++ )
196 img0 = cvLoadImage( names[i], 1 );
199 printf("Couldn't load %s\n", names[i] );
202 img = cvCloneImage( img0 );
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 );
208 // find and draw the squares
209 drawSquares( img, findSquares4( img, storage ) );
212 // Also the function cvWaitKey takes care of event processing
214 // release both images
215 cvReleaseImage( &img );
216 cvReleaseImage( &img0 );
217 // clear memory storage - reset free space position
218 cvClearMemStorage( storage );
223 cvDestroyWindow( wndname );