19c2b53eb852ab06d8574a050d659df0128b2e56
[opencv] / samples / swig_python / minarea.py
1 #!/usr/bin/python 
2
3 from opencv.cv import *
4 from opencv.highgui import *
5 from random import randint
6
7 def minarea_array(img, count):
8     pointMat = cvCreateMat( count, 1, CV_32SC2 )
9     for i in range(count):
10         pointMat[i] = cvPoint( randint(img.width/4, img.width*3/4),
11                                randint(img.height/4, img.height*3/4) )
12
13     box = cvMinAreaRect2( pointMat )
14     box_vtx = cvBoxPoints( box )
15     success, center, radius = cvMinEnclosingCircle( pointMat )
16     cvZero( img )
17     for i in range(count):
18         cvCircle( img, cvGet1D(pointMat,i), 2, CV_RGB( 255, 0, 0 ), CV_FILLED, CV_AA, 0 )
19
20     box_vtx = [cvPointFrom32f(box_vtx[0]),
21                cvPointFrom32f(box_vtx[1]),
22                cvPointFrom32f(box_vtx[2]),
23                cvPointFrom32f(box_vtx[3])]
24     cvCircle( img, cvPointFrom32f(center), cvRound(radius), CV_RGB(255, 255, 0), 1, CV_AA, 0 )
25     cvPolyLine( img, [box_vtx], 1, CV_RGB(0,255,255), 1, CV_AA ) 
26     
27
28     
29 def minarea_seq(img, count, storage):
30     ptseq = cvCreateSeq( CV_SEQ_KIND_GENERIC | CV_32SC2, sizeof_CvContour, sizeof_CvPoint, storage )
31     ptseq = CvSeq_CvPoint.cast( ptseq )
32     for i in range(count):
33         pt0 = cvPoint( randint(img.width/4, img.width*3/4),
34                        randint(img.height/4, img.height*3/4) )
35         cvSeqPush( ptseq, pt0 )
36     box = cvMinAreaRect2( ptseq )
37     box_vtx = cvBoxPoints( box )
38     success, center, radius = cvMinEnclosingCircle( ptseq )
39     cvZero( img )
40     for pt in ptseq: 
41         cvCircle( img, pt, 2, CV_RGB( 255, 0, 0 ), CV_FILLED, CV_AA, 0 )
42
43     box_vtx = [cvPointFrom32f(box_vtx[0]),
44                cvPointFrom32f(box_vtx[1]),
45                cvPointFrom32f(box_vtx[2]),
46                cvPointFrom32f(box_vtx[3])]
47     cvCircle( img, cvPointFrom32f(center), cvRound(radius), CV_RGB(255, 255, 0), 1, CV_AA, 0 )
48     cvPolyLine( img, [box_vtx], 1, CV_RGB(0,255,255), 1, CV_AA ) 
49     cvClearMemStorage( storage )
50
51 if __name__ == "__main__":
52     img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
53     storage = cvCreateMemStorage(0);
54
55     cvNamedWindow( "rect & circle", 1 );
56         
57     use_seq=True
58
59     while True: 
60         count = randint(1,100)
61         if use_seq:
62             minarea_seq(img, count, storage)
63         else:
64             minarea_array(img, count)
65
66         cvShowImage("rect & circle", img)
67         key = cvWaitKey()
68         if( key == '\x1b' ):
69             break;
70
71         use_seq = not use_seq