File: minarea.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 (61 lines) | stat: -rwxr-xr-x 1,736 bytes parent folder | download
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
#!/usr/bin/python 

import urllib2
import cv
from random import randint

def roundxy(pt):
    return (cv.Round(pt[0]), cv.Round(pt[1]))

def draw_common(points):
    success, center, radius = cv.MinEnclosingCircle(points)
    if success:
        cv.Circle(img, roundxy(center), cv.Round(radius), cv.CV_RGB(255, 255, 0), 1, cv. CV_AA, 0)

    box = cv.MinAreaRect2(points)
    box_vtx = [roundxy(p) for p in cv.BoxPoints(box)]
    cv.PolyLine(img, [box_vtx], 1, cv.CV_RGB(0, 255, 255), 1, cv. CV_AA) 

def minarea_array(img, count):
    pointMat = cv.CreateMat(count, 1, cv.CV_32SC2)
    for i in range(count):
        pointMat[i, 0] = (randint(img.width/4, img.width*3/4),
                               randint(img.height/4, img.height*3/4))

    cv.Zero(img)

    for i in range(count):
        cv.Circle(img, roundxy(pointMat[i, 0]), 2, cv.CV_RGB(255, 0, 0), cv.CV_FILLED, cv. CV_AA, 0)

    draw_common(pointMat)

def minarea_seq(img, count, storage):
    points = [(randint(img.width/4, img.width*3/4), randint(img.height/4, img.height*3/4)) for i in range(count)]
    cv.Zero(img)

    for p in points:
        cv.Circle(img, roundxy(p), 2, cv.CV_RGB(255, 0, 0), cv.CV_FILLED, cv. CV_AA, 0)

    draw_common(points)

if __name__ == "__main__":
    img = cv.CreateImage((500, 500), 8, 3)
    storage = cv.CreateMemStorage()

    cv.NamedWindow("rect & circle", 1)
        
    use_seq = True

    while True: 
        count = randint(1, 100)
        if use_seq:
            minarea_seq(img, count, storage)
        else:
            minarea_array(img, count)

        cv.ShowImage("rect & circle", img)
        key = cv.WaitKey() % 0x100
        if key in [27, ord('q'), ord('Q')]:
            break

        use_seq = not use_seq