Update to 2.0.0 tree from current Fremantle build
[opencv] / samples / c / convexhull.c
1 #ifdef _CH_
2 #pragma package <opencv>
3 #endif
4
5 #define CV_NO_BACKWARD_COMPATIBILITY
6
7 #ifndef _EiC
8 #include "cv.h"
9 #include "highgui.h"
10 #include <stdlib.h>
11 #endif
12
13 #define ARRAY  1
14
15 int main( int argc, char** argv )
16 {
17     IplImage* img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
18 #if !ARRAY
19     CvMemStorage* storage = cvCreateMemStorage(0);
20 #endif
21
22     cvNamedWindow( "hull", 1 );
23
24     for(;;)
25     {
26         char key;
27         int i, count = rand()%100 + 1, hullcount;
28         CvPoint pt0;
29 #if !ARRAY
30         CvSeq* ptseq = cvCreateSeq( CV_SEQ_KIND_GENERIC|CV_32SC2, sizeof(CvContour),
31                                      sizeof(CvPoint), storage );
32         CvSeq* hull;
33
34         for( i = 0; i < count; i++ )
35         {
36             pt0.x = rand() % (img->width/2) + img->width/4;
37             pt0.y = rand() % (img->height/2) + img->height/4;
38             cvSeqPush( ptseq, &pt0 );
39         }
40         hull = cvConvexHull2( ptseq, 0, CV_CLOCKWISE, 0 );
41         hullcount = hull->total;
42 #else
43         CvPoint* points = (CvPoint*)malloc( count * sizeof(points[0]));
44         int* hull = (int*)malloc( count * sizeof(hull[0]));
45         CvMat pointMat = cvMat( 1, count, CV_32SC2, points );
46         CvMat hullMat = cvMat( 1, count, CV_32SC1, hull );
47
48         for( i = 0; i < count; i++ )
49         {
50             pt0.x = rand() % (img->width/2) + img->width/4;
51             pt0.y = rand() % (img->height/2) + img->height/4;
52             points[i] = pt0;
53         }
54         cvConvexHull2( &pointMat, &hullMat, CV_CLOCKWISE, 0 );
55         hullcount = hullMat.cols;
56 #endif
57         cvZero( img );
58         for( i = 0; i < count; i++ )
59         {
60 #if !ARRAY
61             pt0 = *CV_GET_SEQ_ELEM( CvPoint, ptseq, i );
62 #else
63             pt0 = points[i];
64 #endif
65             cvCircle( img, pt0, 2, CV_RGB( 255, 0, 0 ), CV_FILLED, CV_AA, 0 );
66         }
67
68 #if !ARRAY
69         pt0 = **CV_GET_SEQ_ELEM( CvPoint*, hull, hullcount - 1 );
70 #else
71         pt0 = points[hull[hullcount-1]];
72 #endif
73
74         for( i = 0; i < hullcount; i++ )
75         {
76 #if !ARRAY
77             CvPoint pt = **CV_GET_SEQ_ELEM( CvPoint*, hull, i );
78 #else
79             CvPoint pt = points[hull[i]];
80 #endif
81             cvLine( img, pt0, pt, CV_RGB( 0, 255, 0 ), 1, CV_AA, 0 );
82             pt0 = pt;
83         }
84
85         cvShowImage( "hull", img );
86
87         key = (char) cvWaitKey(0);
88         if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
89             break;
90
91 #if !ARRAY
92         cvClearMemStorage( storage );
93 #else
94         free( points );
95         free( hull );
96 #endif
97     }
98
99     cvDestroyWindow( "hull" );
100     return 0;
101 }
102
103 #ifdef _EiC
104 main(1,"convexhull.c");
105 #endif
106