2 ## This program is demonstration for ellipse fitting. Program finds
3 ## contours and approximate it by ellipses.
5 ## Trackbar specify threshold parametr.
7 ## White lines is contours. Red lines is fitting ellipses.
9 ## Original C implementation by: Denis Burenkov.
10 ## Python implementation by: Roman Stanchak
11 ## Octave implementation by: Xavier Delacour
21 function process_image( slider_pos )
26 ## Define trackbar callback functon. This function find contours,
27 ## draw it and approximate it by ellipses.
28 stor = cv.cvCreateMemStorage(0);
30 ## Threshold the source image. This needful for cv.cvFindContours().
31 cv.cvThreshold( g.image03, g.image02, slider_pos, 255, cv.CV_THRESH_BINARY );
34 [nb_contours, cont] = cv.cvFindContours (g.image02,stor,cv.sizeof_CvContour,cv.CV_RETR_LIST,cv.CV_CHAIN_APPROX_NONE,cv.cvPoint (0,0));
36 ## Clear images. IPL use.
40 ## This cycle draw all contours and approximate it by ellipses.
41 for c = cv.CvSeq_hrange(cont),
43 count = c.total; # This is number point in contour
45 ## Number point must be more than or equal to 6 (for cv.cvFitEllipse_32f).
50 ## Alloc memory for contour point set.
51 PointArray = cv.cvCreateMat(1, count, cv.CV_32SC2);
52 PointArray2D32f= cv.cvCreateMat( 1, count, cv.CV_32FC2);
54 ## Get contour point set.
55 cv.cvCvtSeqToArray(c, PointArray, cv.cvSlice(0, cv.CV_WHOLE_SEQ_END_INDEX));
57 ## Convert CvPoint set to CvBox2D32f set.
58 cv.cvConvert( PointArray, PointArray2D32f );
62 ## Fits ellipse to current contour.
63 box = cv.cvFitEllipse2(PointArray2D32f);
65 ## Draw current contour.
66 cv.cvDrawContours(g.image04, c, cv.CV_RGB(255,255,255), cv.CV_RGB(255,255,255),0,1,8,cv.cvPoint(0,0));
68 ## Convert ellipse data from float to integer representation.
69 center = cv.CvPoint();
71 center.x = cv.cvRound(box.center.x);
72 center.y = cv.cvRound(box.center.y);
73 size.width = cv.cvRound(box.size.width*0.5);
74 size.height = cv.cvRound(box.size.height*0.5);
75 box.angle = -box.angle;
78 cv.cvEllipse(g.image04, center, size,box.angle, 0, 360,cv.CV_RGB(0,0,255), 1, cv.CV_AA, 0);
81 ## Show image. HighGUI use.
82 highgui.cvShowImage( "Result", g.image04 );
86 filename = "../c/stuff.jpg";
93 ## load image and force it to be grayscale
94 g.image03 = highgui.cvLoadImage(filename, 0);
95 if (!swig_this( g.image03))
96 printf("Could not load image %s\n", filename);
100 ## Create the destination images
101 g.image02 = cv.cvCloneImage( g.image03 );
102 g.image04 = cv.cvCloneImage( g.image03 );
105 highgui.cvNamedWindow("Source", 1);
106 highgui.cvNamedWindow("Result", 1);
109 highgui.cvShowImage("Source", g.image03);
111 ## Create toolbars. HighGUI use.
112 highgui.cvCreateTrackbar( "Threshold", "Result", slider_pos, 255, @process_image );
117 ## Wait for a key stroke; the same function arranges events processing
118 printf("Press any key to exit\n");
119 highgui.cvWaitKey(0);
121 highgui.cvDestroyWindow("Source");
122 highgui.cvDestroyWindow("Result");