[ACCEPTED]-How to calculate convex hull area using openCV functions?-opencv
Accepted answer
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)));
0
Actually calculating the area of 2D convex 7 hull is pretty easy. You integrate the area 6 below each point going in clockwise direction. Here 5 is a simple code that does that. (Few first 4 lines are definition and calculation of 3 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 2 be negative if integration was started from 1 right to left.
use:
CvSeq* convex_hull=cvConvexHull2( &point_mat, &hull_mat, CV_CLOCKWISE, **1** ); // !!
my code:
CvMemStorage* storage = cvCreateMemStorage(0);
CvSeq* contours = 0;
cvFindContours(bordImage, storage, &contours, sizeof(CvContour),
CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));
for(CvSeq* seq = contours; seq != 0; seq = seq->h_next){
cvDrawContours(dstImage, seq, CV_RGB(255,216,0), CV_RGB(0,0,250), 0, 1, 8);
}
CvMemStorage* hullStorage = cvCreateMemStorage(0);
for(CvSeq* seq = contours; seq != 0; seq = seq->h_next){
CvSeq *hulls = cvConvexHull2(seq, hullStorage, CV_CLOCKWISE, 1);
cvDrawContours(dstImage, hulls, CV_RGB(255, 0, 0), CV_RGB(100, 0, 0), 0, 1, 8);
for (int i = 0; i < hulls->total; i++) {
CvPoint* p = (CvPoint*)cvGetSeqElem ( hulls, i );
// ...
}
cvClearMemStorage(hullStorage);
}
0
In OpenCV 2.4.9:
double computeConvexHullArea(vector<Point> originalPoints)
{
vector<Point> hull;
convexHull(originalPoints, hull);
return contourArea(hull);
}
0
For OpenCV python:
hull = cv2.convexHull(cntr) #cntr is the contour
convex_hull_area = cv2.contourArea(hull)
0
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.