物体的凸包(Convex hull)用于理解物体的形状或轮廓。很多复杂物体的特性都能很好的被这种缺陷表现出来。 一组平面上的点,求一个包含所有点的最小的凸多边形,这就是凸包问题了。这可以形象地想成这样:在地上放置一些不可移动的木桩,用一根绳子把他们尽量紧地圈起来,这就是凸包了。
凸包有什么应用?
凸包在很多地方有着重要的应用,如手势识别,需要识别出手的轮廓的凸包,二维或者三维区域的边界的信息等。
凸缺陷。深色的轮廓是围绕手的凸包,格子区域(A-H)是手的凸包,格子区域是手的轮廓相对于凸包的凸缺陷。
相关API:
convexHull
convexHull(contours[i], hull[i], false);
相关参数介绍:
contours[i]:轮廓i点
hull[i]:凸包i的点
bool clockwise:bool变量,表示求得的凸包是顺时针方向还是逆时针方向,true是顺时针方向,false为逆时针方向
bool returnPoints:bool变量,表示是否返回凸包点
程序:
#include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace cv; using namespace std; Mat src; Mat src_gray; int thresh = 100; int max_thresh = 255; RNG rng(12345); /// Function header void thresh_callback(int, void* ); /** @function main */ int main( int argc, char** argv ) { /// 加载源图像 src = imread( "1.jpg", 1 ); /// 转成灰度图并进行模糊降噪 cvtColor( src, src_gray, CV_BGR2GRAY ); blur( src_gray, src_gray, Size(3,3) ); /// 创建窗体 char* source_window = "Source"; namedWindow( source_window, CV_WINDOW_AUTOSIZE ); imshow( source_window, src ); createTrackbar( " Threshold:", "Source", &thresh, max_thresh, thresh_callback ); thresh_callback( 0, 0 ); waitKey(0); return(0); } /** @function thresh_callback */ void thresh_callback(int, void* ) { Mat src_copy = src.clone(); Mat threshold_output; vector<vector<Point> > contours; vector<Vec4i> hierarchy; /// 对图像进行二值化 threshold( src_gray, threshold_output, thresh, 255, THRESH_BINARY ); /// 寻找轮廓 findContours( threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) ); /// 对每个轮廓计算其凸包 vector<vector<Point> >hull( contours.size() ); for( int i = 0; i < contours.size(); i++ ) { convexHull( Mat(contours[i]), hull[i], false ); } /// 绘出轮廓及其凸包 Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 ); for( int i = 0; i< contours.size(); i++ ) { Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); drawContours( drawing, contours, i, color, 1, 8, vector<Vec4i>(), 0, Point() ); drawContours( drawing, hull, i, color, 1, 8, vector<Vec4i>(), 0, Point() ); } /// 把结果显示在窗体 namedWindow( "Hull demo", CV_WINDOW_AUTOSIZE ); imshow( "Hull demo", drawing ); }
效果:
————————————————
版权声明:本文为CSDN博主「南山二毛」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_16481211/article/details/79640863

