3 This program is demonstration for ellipse fitting. Program finds
4 contours and approximate it by ellipses.
6 Trackbar specify threshold parametr.
8 White lines is contours. Red lines is fitting ellipses.
10 Original C implementation by: Denis Burenkov.
11 Python implementation by: Roman Stanchak
16 from opencv import highgui
22 def process_image( slider_pos ):
24 Define trackbar callback functon. This function find contours,
25 draw it and approximate it by ellipses.
27 stor = cv.cvCreateMemStorage(0);
29 # Threshold the source image. This needful for cv.cvFindContours().
30 cv.cvThreshold( image03, image02, slider_pos, 255, cv.CV_THRESH_BINARY );
33 nb_contours, cont = cv.cvFindContours (image02,
37 cv.CV_CHAIN_APPROX_NONE,
40 # Clear images. IPL use.
44 # This cycle draw all contours and approximate it by ellipses.
45 for c in cont.hrange():
46 count = c.total; # This is number point in contour
48 # Number point must be more than or equal to 6 (for cv.cvFitEllipse_32f).
52 # Alloc memory for contour point set.
53 PointArray = cv.cvCreateMat(1, count, cv.CV_32SC2)
54 PointArray2D32f= cv.cvCreateMat( 1, count, cv.CV_32FC2)
56 # Get contour point set.
57 cv.cvCvtSeqToArray(c, PointArray, cv.cvSlice(0, cv.CV_WHOLE_SEQ_END_INDEX));
59 # Convert CvPoint set to CvBox2D32f set.
60 cv.cvConvert( PointArray, PointArray2D32f )
64 # Fits ellipse to current contour.
65 box = cv.cvFitEllipse2(PointArray2D32f);
67 # Draw current contour.
68 cv.cvDrawContours(image04, c, cv.CV_RGB(255,255,255), cv.CV_RGB(255,255,255),0,1,8,cv.cvPoint(0,0));
70 # Convert ellipse data from float to integer representation.
73 center.x = cv.cvRound(box.center.x);
74 center.y = cv.cvRound(box.center.y);
75 size.width = cv.cvRound(box.size.width*0.5);
76 size.height = cv.cvRound(box.size.height*0.5);
77 box.angle = -box.angle;
80 cv.cvEllipse(image04, center, size,
82 cv.CV_RGB(0,0,255), 1, cv.CV_AA, 0);
84 # Show image. HighGUI use.
85 highgui.cvShowImage( "Result", image04 );
88 if __name__ == '__main__':
90 filename = "../c/stuff.jpg"
92 filename = sys.argv[1]
96 # load image and force it to be grayscale
97 image03 = highgui.cvLoadImage(filename, 0)
99 print "Could not load image " + filename
102 # Create the destination images
103 image02 = cv.cvCloneImage( image03 );
104 image04 = cv.cvCloneImage( image03 );
107 highgui.cvNamedWindow("Source", 1);
108 highgui.cvNamedWindow("Result", 1);
111 highgui.cvShowImage("Source", image03);
113 # Create toolbars. HighGUI use.
114 highgui.cvCreateTrackbar( "Threshold", "Result", slider_pos, 255, process_image );
119 #Wait for a key stroke; the same function arranges events processing
120 print "Press any key to exit"
121 highgui.cvWaitKey(0);
123 highgui.cvDestroyWindow("Source");
124 highgui.cvDestroyWindow("Result");