3 print "OpenCV Python version of contours"
5 # import the necessary things for OpenCV
7 from opencv import highgui
9 # some default constants
13 # definition of some colors
14 _red = cv.cvScalar (0, 0, 255, 0);
15 _green = cv.cvScalar (0, 255, 0, 0);
16 _white = cv.cvRealScalar (255)
17 _black = cv.cvRealScalar (0)
19 # the callback on the trackbar, to set the level of contours we want
21 def on_trackbar (position):
23 # create the image for putting in it the founded contours
24 contours_image = cv.cvCreateImage (cv.cvSize (_SIZE, _SIZE), 8, 3)
26 # compute the real level of display, given the current position
33 # zero or negative value
34 # => get to the nearest face to make it look more funny
35 _contours = contours.h_next.h_next.h_next
37 # first, clear the image where we will draw contours
38 cv.cvSetZero (contours_image)
40 # draw contours in red and green
41 cv.cvDrawContours (contours_image, _contours,
46 # finally, show the image
47 highgui.cvShowImage ("contours", contours_image)
49 if __name__ == '__main__':
51 # create the image where we want to display results
52 image = cv.cvCreateImage (cv.cvSize (_SIZE, _SIZE), 8, 1)
54 # start with an empty image
57 # draw the original picture
59 dx = (i % 2) * 250 - 30
63 cv.cvPoint (dx + 150, dy + 100),
65 0, 0, 360, _white, -1, 8, 0)
67 cv.cvPoint (dx + 115, dy + 70),
69 0, 0, 360, _black, -1, 8, 0)
71 cv.cvPoint (dx + 185, dy + 70),
73 0, 0, 360, _black, -1, 8, 0)
75 cv.cvPoint (dx + 115, dy + 70),
77 0, 0, 360, _white, -1, 8, 0)
79 cv.cvPoint (dx + 185, dy + 70),
81 0, 0, 360, _white, -1, 8, 0)
83 cv.cvPoint (dx + 115, dy + 70),
85 0, 0, 360, _black, -1, 8, 0)
87 cv.cvPoint (dx + 185, dy + 70),
89 0, 0, 360, _black, -1, 8, 0)
91 cv.cvPoint (dx + 150, dy + 100),
93 0, 0, 360, _black, -1, 8, 0)
95 cv.cvPoint (dx + 150, dy + 150),
97 0, 0, 360, _black, -1, 8, 0)
99 cv.cvPoint (dx + 27, dy + 100),
101 0, 0, 360, _white, -1, 8, 0)
103 cv.cvPoint (dx + 273, dy + 100),
105 0, 0, 360, _white, -1, 8, 0)
107 # create window and display the original picture in it
108 highgui.cvNamedWindow ("image", 1)
109 highgui.cvShowImage ("image", image)
111 # create the storage area
112 storage = cv.cvCreateMemStorage (0)
115 nb_contours, contours = cv.cvFindContours (image,
119 cv.CV_CHAIN_APPROX_SIMPLE,
122 # comment this out if you do not want approximation
123 contours = cv.cvApproxPoly (contours, cv.sizeof_CvContour,
125 cv.CV_POLY_APPROX_DP, 3, 1)
127 # create the window for the contours
128 highgui.cvNamedWindow ("contours", 1)
130 # create the trackbar, to enable the change of the displayed level
131 highgui.cvCreateTrackbar ("levels+3", "contours", 3, 7, on_trackbar)
133 # call one time the callback, so we will have the 1st display done
134 on_trackbar (_DEFAULT_LEVEL)
136 # wait a key pressed to end
137 highgui.cvWaitKey (0)