Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate convex hull area using openCV functions?

Tags:

c

opencv

I'm unable to find a working example of how to calculate the area of a convex hull using OpenCV. I saw one example that uses cvApproxPoly and cvContourArea, but I couldn't make it work. I have the following code.

IplImage* img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );


int i, count = rand()%100 + 1;
CvPoint pt0;

CvPoint* points = (CvPoint*)malloc( count * sizeof(points[0]));
int* hull = (int*)malloc( count * sizeof(hull[0]));
CvMat point_mat = cvMat( 1, count, CV_32SC2, points );
CvMat hull_mat  = cvMat( 1, count, CV_32SC1, hull );        
for( i = 0; i < count; i++ )
{
    pt0.x = rand() % (img->width/2) + img->width/4;
    pt0.y = rand() % (img->height/2) + img->height/4;
    points[i] = pt0;
}


CvSeq* convex_hull=cvConvexHull2( &point_mat, &hull_mat, CV_CLOCKWISE, 0 );
like image 403
Gorayni Avatar asked Nov 28 '22 10:11

Gorayni


2 Answers

Actually calculating the area of 2D convex hull is pretty easy. You integrate the area below each point going in clockwise direction. Here is a simple code that does that. (Few first lines are definition and calculation of convex hull).

vector<Point2f> originalPoints;   // Your original points
vector<Point2f> ch;  // Convex hull points

// Calculate convex hull of original points (which points positioned on the boundary)
cv::convexHull(Mat(originalPoints),ch,false);
// false parameter is used to organize the points in clockwise direction

// Now calculate the area of sonvex hull 'ch':
double area = 0;
for (int i = 0; i < ch.size(); i++){
    int next_i = (i+1)%(ch.size());
    double dX   = ch[next_i].x - ch[i].x;
    double avgY = (ch[next_i].y + ch[i].y)/2;
    area += dX*avgY;  // This is the integration step.
}

area = abs(area); // Area can be negative if integration was started from right to left.

like image 23
DanielHsH Avatar answered Dec 01 '22 00:12

DanielHsH


    vector<Point2f> originalPoints;   // Your original points
    vector<Point2f> convexHull;  // Convex hull points 
    vector<Point2f> contour;  // Convex hull contour points        
    double epsilon = 0.001; // Contour approximation accuracy

    // Calculate convex hull of original points (which points positioned on the boundary)
    convexHull(Mat(originalPoints),convexHull,false);

    // Approximating polygonal curve to convex hull
    approxPolyDP(Mat(convexHull), contour, 0.001, true);

    cout << fabs(contourArea(Mat(contour)));
like image 67
Gorayni Avatar answered Dec 01 '22 00:12

Gorayni