Goal
在本教程中,您将学习如何:
使用 OpenCV 函数 cv::convexHull
Theory
Code
本教程代码如下所示。 你也可以从这里下载https://github.com/opencv/opencv/tree/4.x/samples/cpp/tutorial_code/ShapeDescriptors/hull_demo.cpp
/**
* @function hull_demo.cpp
* @brief 在图像中查找轮廓的演示代码
* @author OpenCV team
*/
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
Mat src_gray;
int thresh = 100;
RNG rng(12345);
/// 函数头
void thresh_callback(int, void* );
/**
* @function 主函数
*/
int main( int argc, char** argv )
{
/// 加载源图像并将其转换为灰色
CommandLineParser parser( argc, argv, "{@input | stuff.jpg | input image}" );
Mat src = imread( samples::findFile( parser.get<String>( "@input" ) ) );
if( src.empty() )
{
cout << "Could not open or find the image!\n" << endl;
cout << "Usage: " << argv[0] << " <Input image>" << endl;
return -1;
}
///将图像转换为灰色并模糊它
cvtColor( src, src_gray, COLOR_BGR2GRAY );
blur( src_gray, src_gray, Size(3,3) );
/// 创建窗口
const char* source_window = "Source";//窗口名
namedWindow( source_window );//定义窗口
imshow( source_window, src );//在窗口中显示源图像
const int max_thresh = 255;//滑动条绑定的变量
createTrackbar( "Canny thresh:", source_window, &thresh, max_thresh, thresh_callback );//创建滑动条
thresh_callback( 0, 0 );//回调
waitKey();
return 0;
}
/**
* @function thresh_callback
*/
void thresh_callback(int, void* )
{
///使用 Canny 检测边缘
Mat canny_output;
Canny( src_gray, canny_output, thresh, thresh*2 );
/// 找到轮廓
vector<vector<Point> > contours;
findContours( canny_output, contours, RETR_TREE, CHAIN_APPROX_SIMPLE );
/// 找到每个轮廓的凸包对象 Find the convex hull object for each contour
vector<vector<Point> >hull( contours.size() );
for( size_t i = 0; i < contours.size(); i++ )
{
convexHull( contours[i], hull[i] );//每个轮廓 生成一个凸包
}
/// 绘制轮廓和凸包结果 Draw contours + hull results
Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );//黑色背景图
for( size_t i = 0; i< contours.size(); i++ )
{
Scalar color = Scalar( rng.uniform(0, 256), rng.uniform(0,256), rng.uniform(0,256) );//随机颜色
drawContours( drawing, contours, (int)i, color );//绘制轮廓
drawContours( drawing, hull, (int)i, color );//绘制凸包
}
/// 在窗口中显示 Show in a window
imshow( "Hull demo", drawing );
}
Explanation
Result