3 from opencv.cv import *
4 from opencv.highgui import *
5 from random import randint
7 def minarea_array(img, count):
8 pointMat = cvCreateMat( count, 1, CV_32SC2 )
10 pointMat[i] = cvPoint( randint(img.width/4, img.width*3/4),
11 randint(img.height/4, img.height*3/4) )
13 box = cvMinAreaRect2( pointMat )
14 box_vtx = cvBoxPoints( box )
15 success, center, radius = cvMinEnclosingCircle( pointMat )
17 for i in range(count):
18 cvCircle( img, cvGet1D(pointMat,i), 2, CV_RGB( 255, 0, 0 ), CV_FILLED, CV_AA, 0 )
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 )
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 )
41 cvCircle( img, pt, 2, CV_RGB( 255, 0, 0 ), CV_FILLED, CV_AA, 0 )
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 )
51 if __name__ == "__main__":
52 img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
53 storage = cvCreateMemStorage(0);
55 cvNamedWindow( "rect & circle", 1 );
60 count = randint(1,100)
62 minarea_seq(img, count, storage)
64 minarea_array(img, count)
66 cvShowImage("rect & circle", img)