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 (71 lines) | stat: -rwxr-xr-x 2,429 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
#!/usr/bin/python 

from opencv.cv import *
from opencv.highgui import *
from random import randint

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

    box = cvMinAreaRect2( pointMat )
    box_vtx = cvBoxPoints( box )
    success, center, radius = cvMinEnclosingCircle( pointMat )
    cvZero( img )
    for i in range(count):
        cvCircle( img, cvGet1D(pointMat,i), 2, CV_RGB( 255, 0, 0 ), CV_FILLED, CV_AA, 0 )

    box_vtx = [cvPointFrom32f(box_vtx[0]),
               cvPointFrom32f(box_vtx[1]),
               cvPointFrom32f(box_vtx[2]),
               cvPointFrom32f(box_vtx[3])]
    cvCircle( img, cvPointFrom32f(center), cvRound(radius), CV_RGB(255, 255, 0), 1, CV_AA, 0 )
    cvPolyLine( img, [box_vtx], 1, CV_RGB(0,255,255), 1, CV_AA ) 
    

    
def minarea_seq(img, count, storage):
    ptseq = cvCreateSeq( CV_SEQ_KIND_GENERIC | CV_32SC2, sizeof_CvContour, sizeof_CvPoint, storage )
    ptseq = CvSeq_CvPoint.cast( ptseq )
    for i in range(count):
        pt0 = cvPoint( randint(img.width/4, img.width*3/4),
                       randint(img.height/4, img.height*3/4) )
        cvSeqPush( ptseq, pt0 )
    box = cvMinAreaRect2( ptseq )
    box_vtx = cvBoxPoints( box )
    success, center, radius = cvMinEnclosingCircle( ptseq )
    cvZero( img )
    for pt in ptseq: 
        cvCircle( img, pt, 2, CV_RGB( 255, 0, 0 ), CV_FILLED, CV_AA, 0 )

    box_vtx = [cvPointFrom32f(box_vtx[0]),
               cvPointFrom32f(box_vtx[1]),
               cvPointFrom32f(box_vtx[2]),
               cvPointFrom32f(box_vtx[3])]
    cvCircle( img, cvPointFrom32f(center), cvRound(radius), CV_RGB(255, 255, 0), 1, CV_AA, 0 )
    cvPolyLine( img, [box_vtx], 1, CV_RGB(0,255,255), 1, CV_AA ) 
    cvClearMemStorage( storage )

if __name__ == "__main__":
    img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
    storage = cvCreateMemStorage(0);

    cvNamedWindow( "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)

        cvShowImage("rect & circle", img)
        key = cvWaitKey()
        if( key == '\x1b' ):
            break;

        use_seq = not use_seq