30. Convex Hull

1. Main content

  • Concept introduction
  • API description
  • Code demo

2. Concept introduction

  • What is a convex hull (Convex Hull), the line between any two points on a multi-deformed edge or inside is included in the polygon boundary or inside.
  • Formal definition: the smallest convex polygon containing all points in the point set S is called the convex hull
    Insert picture description here
    detection algorithm-Graham scanning method (a more commonly used algorithm)
    Insert picture description here

3. Introduction to Graham Scanning Method

  • First select the lowest point in the Y direction as the starting point p0
  • Start polar coordinate scanning from p0, add p1 .... pn in sequence (the sorting order is based on the angle of polar coordinates, counterclockwise)
  • For each point pi, if adding a pi point to the convex hull results in a left turn (counterclockwise method), then add that point to the convex hull, otherwise if it causes a right turn (clockwise direction), delete the point from the convex hull in

All we need
to know is that we need to understand that OpenCV has implemented a convex hull discovery algorithm and API for us to use.
The algorithm is based on the following picture to learn and understand
Insert picture description here

4. API description cv :: convexHull

convexHull(
InputArray points,// 输入候选点,来自findContours
OutputArray hull,// 凸包
bool clockwise,// default true, 顺时针方向
bool returnPoints)// true 表示返回点个数,如果第二个参数是vector<Point>则自动忽略

5. Code demo:

Main steps:
1. First convert the image from RGB to grayscale
2. Then convert to the binary image
3. Obtain candidate points by finding the contour
4. Convex hull API call
5. Draw and display.

cvtColor(src,src_gray,CV_BGR2GRAY);
blur(src_gray,src_gray,Size(3,3),Point(-1,-1));

void Threshold_Callback(int ,void*){
    Mat threshold_output;
    vector<vector<Point>>contours;
    vector<Vec4i>hierarchy;
    
     threshold(src_gray,threshold_output,threshold_value,255,THRESH_BINARY)
    findContours(threshold_output,contours,hierarchy,RETR_TREE,CHAIN_APPROX_SIMOPLE,POint(0,0));
    
    vector<vector<Point>>hull(contours.size());//存放凸包的点集(此处进行初始化)
    for(size_t i=0;i<contours.size();i++){
        convexHull(Mat(contours[i]),hull[i],false)
    }
    
    Mat dst= Mat::zeros(threshold_output,size(),CV_8UC3);
    for(size_t i = 0;i < contours.size();i++){
        Scalar color = Scalar (rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255))       
        drawContours(dst,hull,i,color,1,LINE_8,hierarchy,0,Point(0,0));
        drawContours(dst,contours,i,color,1,LINE_8,hierarchy,0,Point(0,0));
       }
   imshow(output_win,dst);    
}

6. Extracurricular expansion

Convex hull
lconvexHull () function
computer screen coordinate system
threshold () function

Published 66 original articles · won praise 53 · views 6812

Guess you like

Origin blog.csdn.net/qq_43367829/article/details/105424816
Recommended