Lesson 30 convex hull (Convex Hull)

1. What is the convex hull

  • In a multi-connection or an internal modification of any two edge points are included in a polygon edge or the inside.
    Here Insert Picture Description
  • Minimum convex point set S containing all points in the convex hull polygon is called

Here Insert Picture Description

  • Convex hull scanning detection algorithm --Graham

2. Graham scan algorithm

  • First, choose the lowest point in the Y direction as a starting point p0
  • From the polar coordinates p0 start scanning sequentially adding p1 ... .pn (sort order based on the size of the polar angle, counterclockwise direction)
  • For each point pi, pi is added if the convex hull points to cause a left turn (counterclockwise method) is added to the convex hull points, whereas if a right turn leads (clockwise) to remove the point from the convex hull in
    Here Insert Picture Description

3. Step

  1. First, the image from RGB to gray
  2. And then converted to a binary image
  3. Then obtained by finding the contour candidate point
  4. Convex hull API calls
  5. Draw display.

4. Related API

4.1 cv::convexHull()

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

5. Routine

#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>

using namespace cv;
using namespace std;
void CallBack(int, void*);
Mat src, dst, binout, src_gray;
int Threshold = 10;

int main() {
	
	//输入图像并转化为灰度
	src = imread("D:/resource/images/手.png");
	if (src.empty()) {
		printf("src  couldn't be loaded...");
		return -1;
	}
	imshow("input", src);
	
	cvtColor(src, src_gray, COLOR_BGR2GRAY);
	GaussianBlur(src_gray, src_gray, Size(3, 3),0, 0, BORDER_DEFAULT);
	imshow("gray", src_gray);

	//设置阈值后执行CallBack()
	namedWindow("output");
	createTrackbar("Threshold", "output", &Threshold, 255, CallBack);
	CallBack(0, 0);

	waitKey(0);
	return 0;
}

void CallBack(int, void*) {

	//二值化
	threshold(src_gray, binout, Threshold, 255, THRESH_BINARY);

	//寻找边缘
	vector<vector<Point>> contours;
	vector<Vec4i> hierachy;
	findContours(binout, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));

	//凸包检测
	vector<vector<Point>> convexs(contours.size());
	for(size_t k=0;k<contours.size();k++)
		convexHull(contours[k], convexs[k], false, true);

	//画出所有边缘(蓝色)和凸包(红色)
	dst = Mat::zeros(src.size(), CV_8UC3);
	for (size_t i = 0; i < convexs.size(); i++)
	{
		drawContours(dst, contours, i, Scalar(255, 0, 0), 1, LINE_8, Mat());
		drawContours(dst, convexs, i, Scalar(0, 0, 255), 1, LINE_8, Mat());
	}
		imshow("output", dst);
	cout << contours.size()<<endl;
		

}

Here Insert Picture Description

Published 31 original articles · won praise 12 · views 2752

Guess you like

Origin blog.csdn.net/weixin_42877426/article/details/104382198