File: convexhull.py

package info (click to toggle)
opencv 2.1.0-3%2Bsqueeze1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 68,800 kB
  • ctags: 52,010
  • sloc: cpp: 554,793; xml: 475,942; ansic: 153,396; python: 18,622; sh: 428; makefile: 111
file content (78 lines) | stat: -rwxr-xr-x 2,197 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#! /usr/bin/env python

print "OpenCV Python version of convexhull"

# import the necessary things for OpenCV
from opencv import cv
from opencv import highgui

# to generate random values
import random

# how many points we want at max
_MAX_POINTS = 100

if __name__ == '__main__':

    # main object to get random values from
    my_random = random.Random ()

    # create the image where we want to display results
    image = cv.cvCreateImage (cv.cvSize (500, 500), 8, 3)

    # create the window to put the image in
    highgui.cvNamedWindow ('hull', highgui.CV_WINDOW_AUTOSIZE)

    while True:
        # do forever

        # get a random number of points
        count = my_random.randrange (0, _MAX_POINTS) + 1

        # initialisations
        points = []
        
        for i in range (count):
            # generate a random point
            points.append (cv.cvPoint (
                my_random.randrange (0, image.width / 2) + image.width / 4,
                my_random.randrange (0, image.width / 2) + image.width / 4
                ))

        # compute the convex hull
        hull = cv.cvConvexHull2 (points, cv.CV_CLOCKWISE, 0)

        # start with an empty image
        cv.cvSetZero (image)

        for i in range (count):
            # draw all the points
            cv.cvCircle (image, points [i], 2,
                         cv.cvScalar (0, 0, 255, 0),
                         cv.CV_FILLED, cv.CV_AA, 0)

        # start the line from the last point
        pt0 = points [hull [-1]]
        
        for point_index in hull:
            # connect the previous point to the current one

            # get the current one
            pt1 = points [point_index]

            # draw
            cv.cvLine (image, pt0, pt1,
                       cv.cvScalar (0, 255, 0, 0),
                       1, cv.CV_AA, 0)

            # now, current one will be the previous one for the next iteration
            pt0 = pt1

        # display the final image
        highgui.cvShowImage ('hull', image)

        # handle events, and wait a key pressed
        k = highgui.cvWaitKey (0)
        if k == '\x1b':
            # user has press the ESC key, so exit
            break