OpenCV (35): Convex Hull Detection

1. Introduction to convex hull detection

      Convex hull detection is a technique for calculating the convex hull. The convex hull is a convex polygon formed by connecting the outermost points of a given set of points on a two-dimensional plane. It contains all the points in the point set.

2. Convex hull detection function convexHull()

void cv::convexHull ( InputArray  points,

OutputArray hull,

boolclockwise = false,

bool   returnPoints = true

)

  • points: input 2D point set
  • hull: Output the vertices of the convex hull
  • clockwise: direction flag, when the parameter is true, the convex hull order is clockwise, otherwise it is counterclockwise. returnPoints: The type flag of the output data. When the parameter is true, the output result of the second parameter is the coordinate of the convex hull vertex, otherwise the output result of the second parameter is the index of the convex hull vertex.

3. Sample code:


//凸包检测
void Convex_hull_detection(Mat image){
    Mat gray,binary;
    cvtColor(image,gray,COLOR_BGR2GRAY);//灰度化
    threshold(gray,binary,40,255,THRESH_BINARY);//自适应二值化
    //开运算消除细小区域
    Mat k= getStructuringElement(MORPH_RECT,Size(3,3),Point(-1,-1));
    morphologyEx(binary,binary,MORPH_OPEN,k);
    //轮廓的发现与绘制
    vector<vector<Point>> contours;//轮廓
    vector<Vec4i> hierarchy;//存放轮廓结构变量
    findContours(binary,contours,hierarchy,0,2,Point());
   for(int n=0;n<contours.size();n++){
       //计算凸包
       vector<Point> hull;
       convexHull(contours[n],hull);
       //绘制凸包
       for(int i=0;i<hull.size();i++){
           //绘制凸包顶点
           circle(image,hull[i],4,Scalar(255,0,0,255),2,8,0);
           //连接凸包
           if(i==hull.size()-1){
               line(image,hull[i],hull[0],Scalar(0,0,255,255),2,8,0);
               break;
           }
           line(image,hull[i],hull[i-1],Scalar(0,0,255,255),2,8,0);
       }
   }
    imwrite("/sdcard/DCIM/hull.png",image);

}

The results of convex hull detection: 

Guess you like

Origin blog.csdn.net/weixin_63357306/article/details/132792277
Recommended