Update to 2.0.0 tree from current Fremantle build
[opencv] / samples / swig_python / convexhull.py
1 #! /usr/bin/env python
2
3 print "OpenCV Python version of convexhull"
4
5 # import the necessary things for OpenCV
6 from opencv import cv
7 from opencv import highgui
8
9 # to generate random values
10 import random
11
12 # how many points we want at max
13 _MAX_POINTS = 100
14
15 if __name__ == '__main__':
16
17     # main object to get random values from
18     my_random = random.Random ()
19
20     # create the image where we want to display results
21     image = cv.cvCreateImage (cv.cvSize (500, 500), 8, 3)
22
23     # create the window to put the image in
24     highgui.cvNamedWindow ('hull', highgui.CV_WINDOW_AUTOSIZE)
25
26     while True:
27         # do forever
28
29         # get a random number of points
30         count = my_random.randrange (0, _MAX_POINTS) + 1
31
32         # initialisations
33         points = []
34         
35         for i in range (count):
36             # generate a random point
37             points.append (cv.cvPoint (
38                 my_random.randrange (0, image.width / 2) + image.width / 4,
39                 my_random.randrange (0, image.width / 2) + image.width / 4
40                 ))
41
42         # compute the convex hull
43         hull = cv.cvConvexHull2 (points, cv.CV_CLOCKWISE, 0)
44
45         # start with an empty image
46         cv.cvSetZero (image)
47
48         for i in range (count):
49             # draw all the points
50             cv.cvCircle (image, points [i], 2,
51                          cv.cvScalar (0, 0, 255, 0),
52                          cv.CV_FILLED, cv.CV_AA, 0)
53
54         # start the line from the last point
55         pt0 = points [hull [-1]]
56         
57         for point_index in hull:
58             # connect the previous point to the current one
59
60             # get the current one
61             pt1 = points [point_index]
62
63             # draw
64             cv.cvLine (image, pt0, pt1,
65                        cv.cvScalar (0, 255, 0, 0),
66                        1, cv.CV_AA, 0)
67
68             # now, current one will be the previous one for the next iteration
69             pt0 = pt1
70
71         # display the final image
72         highgui.cvShowImage ('hull', image)
73
74         # handle events, and wait a key pressed
75         k = highgui.cvWaitKey (0)
76         if k == '\x1b':
77             # user has press the ESC key, so exit
78             break