在图像处理和分析中,通常会遇到求物体的凸包或某类型形状的凸包,以下函数可以实现该功能:
void get_hull(cv::Mat& src,int thresh) { Mat src_copy = src.clone(); Mat threshold_output; vector<vector<Point> > contours; vector<Vec4i> hierarchy; /// Detect edges using Threshold threshold( src_gray, threshold_output, thresh, 255, THRESH_BINARY ); /// Find contours findContours( threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) ); /// Find the convex hull object for each contour vector<vector<Point> >hull( contours.size() ); for( int i = 0; i < contours.size(); i++ ) { convexHull( Mat(contours[i]), hull[i], false ); } /// Draw contours + hull results 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() ); } }