OpenCv-C++-凸包操作

什么是凸包?简单点就是在一幅图像里面有很多点,而有一些点连成的形状能够把所有点包围进去。
使用OpenCv怎么做?

1、先将图片转化为灰度图像;
2、转化为二值图像;
3、找到图片的全部轮廓点;
4、使用凸包API从全部轮廓点中找到最优轮廓点;
5、连接凸包轮廓点

凸包使用的API是convexHull()

下面看代码:

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

using namespace cv;
using namespace std;

Mat src,dst,gray_src;
int threshold_value = 100;
int threshold_max = 255;

void convexHull(int, void*);
int main(int argc, char** argv)
{
	src = imread("D:/test/small_hand.png");
	if (!src.data)
	{
		cout << "图片为空" << endl;
		return -1;
	}
	blur(src, src, Size(3, 3), Point(-1, -1), BORDER_DEFAULT);
	cvtColor(src, gray_src, CV_BGR2GRAY);
	imshow("input img", gray_src);
	namedWindow("convexHull title",CV_WINDOW_AUTOSIZE);
	createTrackbar("Move", "convexHull title", &threshold_value, threshold_max, convexHull);
	convexHull(0,0);
	waitKey(0);
	return 0;

}

void convexHull(int, void *)
{
	RNG rng(12345);
	
	Mat bin_output;
	vector<vector<Point>> contours;//轮廓点
	vector<Vec4i> hierarcy;
	//转为二值图像
	threshold(gray_src, bin_output, threshold_value, threshold_max, THRESH_BINARY);
	findContours(bin_output, contours, hierarcy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
	vector<vector<Point>> convex(contours.size());//凸包轮廓点
	for (size_t i = 0; i < contours.size(); i++)
	{
		convexHull(contours[i], convex[i], false, true);
	}
	
	//绘制轮廓点
	dst = Mat::zeros(src.size(), CV_8UC3);//图像必须是3通道
	vector<Vec4i> empty(0);
	for (size_t k = 0; k < contours.size(); k++)
	{
		Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
		//绘制整个图像轮廓
		drawContours(dst, contours, (int)k, color, 2, LINE_AA, hierarcy, 0, Point(0, 0));
	    //绘制凸包点
		drawContours(dst, convex, (int)k, color, 2, LINE_AA, empty, 0, Point(0, 0));
	}
	imshow("convexHull title", dst);
}

运行结果
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Daker_Huang/article/details/84647067
今日推荐