3 # The full "Square Detector" program.
4 # It loads several images subsequentally and tries to find squares in
8 from opencv.cv import *
9 from opencv.highgui import *
16 wndname = "Square Detection Demo";
18 def angle( pt1, pt2, pt0 ):
23 return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
25 def findSquares4( img, storage ):
27 sz = cvSize( img.width & -2, img.height & -2 );
28 timg = cvCloneImage( img ); # make a copy of input image
29 gray = cvCreateImage( sz, 8, 1 );
30 pyr = cvCreateImage( cvSize(sz.width/2, sz.height/2), 8, 3 );
31 # create empty sequence that will contain points -
32 # 4 points per square (the square's vertices)
33 squares = cvCreateSeq( 0, sizeof_CvSeq, sizeof_CvPoint, storage );
34 squares = CvSeq_CvPoint.cast( squares )
36 # select the maximum ROI in the image
37 # with the width and height divisible by 2
38 subimage = cvGetSubRect( timg, cvRect( 0, 0, sz.width, sz.height ))
40 # down-scale and upscale the image to filter out the noise
41 cvPyrDown( subimage, pyr, 7 );
42 cvPyrUp( pyr, subimage, 7 );
43 tgray = cvCreateImage( sz, 8, 1 );
44 # find squares in every color plane of the image
46 # extract the c-th color plane
47 channels = [None, None, None]
49 cvSplit( subimage, channels[0], channels[1], channels[2], None )
51 # hack: use Canny instead of zero threshold level.
52 # Canny helps to catch squares with gradient shading
54 # apply Canny. Take the upper threshold from slider
55 # and set the lower to 0 (which forces edges merging)
56 cvCanny( tgray, gray, 0, thresh, 5 );
57 # dilate canny output to remove potential
58 # holes between edge segments
59 cvDilate( gray, gray, None, 1 );
61 # apply threshold if l!=0:
62 # tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
63 cvThreshold( tgray, gray, (l+1)*255/N, 255, CV_THRESH_BINARY );
65 # find contours and store them all as a list
66 count, contours = cvFindContours( gray, storage, sizeof_CvContour,
67 CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) );
73 for contour in contours.hrange():
74 # approximate contour with accuracy proportional
75 # to the contour perimeter
76 result = cvApproxPoly( contour, sizeof_CvContour, storage,
77 CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0 );
78 # square contours should have 4 vertices after approximation
79 # relatively large area (to filter out noisy contours)
81 # Note: absolute value of an area is used because
82 # area may be positive or negative - in accordance with the
84 if( result.total == 4 and
85 abs(cvContourArea(result)) > 1000 and
86 cvCheckContourConvexity(result) ):
89 # find minimum angle between joint
90 # edges (maximum of cosine)
92 t = abs(angle( result[i], result[i-2], result[i-1]))
95 # if cosines of all angles are small
96 # (all angles are ~90 degree) then write quandrange
97 # vertices to resultant sequence
100 squares.append( result[i] )
104 # the function draws all the squares in the image
105 def drawSquares( img, squares ):
106 cpy = cvCloneImage( img );
107 # read 4 sequence elements at a time (all vertices of a square)
109 while i<squares.total:
112 pt.append( squares[i] )
113 pt.append( squares[i+1] )
114 pt.append( squares[i+2] )
115 pt.append( squares[i+3] )
117 # draw the square as a closed polyline
118 cvPolyLine( cpy, [pt], 1, CV_RGB(0,255,0), 3, CV_AA, 0 );
121 # show the resultant image
122 cvShowImage( wndname, cpy );
124 def on_trackbar( a ):
126 drawSquares( img, findSquares4( img, storage ) );
128 names = ["../c/pic1.png", "../c/pic2.png", "../c/pic3.png",
129 "../c/pic4.png", "../c/pic5.png", "../c/pic6.png" ];
131 if __name__ == "__main__":
132 # create memory storage that will contain all the dynamic data
133 storage = cvCreateMemStorage(0);
135 img0 = cvLoadImage( name, 1 );
137 print "Couldn't load %s" % name
139 img = cvCloneImage( img0 );
140 # create window and a trackbar (slider) with parent "image" and set callback
141 # (the slider regulates upper threshold, passed to Canny edge detector)
142 cvNamedWindow( wndname, 1 );
143 cvCreateTrackbar( "canny thresh", wndname, thresh, 1000, on_trackbar );
144 # force the image processing
147 # Also the function cvWaitKey takes care of event processing
149 # clear memory storage - reset free space position
150 cvClearMemStorage( storage );
153 cvDestroyWindow( wndname );