OpenCV
开源计算机视觉库
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
凸包

上一篇教程: 在图像中查找轮廓
下一篇教程: 为轮廓创建边界框和圆圈

原作者Ana Huamán
兼容性OpenCV >= 3.0

目标

在本教程中,您将学习如何:

理论

代码

本教程代码如下所示。您也可以从 这里 下载。

#include <iostream>
using namespace cv;
using namespace std;
Mat src_gray;
int thresh = 100;
RNG rng(12345);
void thresh_callback(int, void* );
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 << "无法打开或找到图像!\n" << endl;
cout << "用法:" << argv[0] << " <输入图像>" << 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 阈值:", source_window, &thresh, max_thresh, thresh_callback );
thresh_callback( 0, 0 );
waitKey();
return 0;
}
void thresh_callback(int, void* )
{
Mat canny_output;
Canny( src_gray, canny_output, thresh, thresh*2 );
vector<vector<Point> > contours;
findContours( canny_output, contours, RETR_TREE, CHAIN_APPROX_SIMPLE );
vector<vector<Point> >hull( contours.size() );
for( size_t i = 0; i < contours.size(); i++ )
{
convexHull( contours[i], hull[i] );
}
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 );
}
imshow( "Hull demo", drawing );
}
用于命令行解析。
定义 utility.hpp:890
N维密集数组类
定义 mat.hpp:829
MatSize size
定义 mat.hpp:2177
bool empty() const
如果数组没有元素,则返回 true。
随机数生成器。
定义 core.hpp:2874
用于指定图像或矩形大小的模板类。
定义 types.hpp:335
std::string String
定义 cvstd.hpp:151
#define CV_8UC3
定义 interface.h:90
void imshow(const String &winname, InputArray mat)
在指定的窗口中显示图像。
int main(int argc, char *argv[])
定义 highgui_qt.cpp:3
定义 core.hpp:107
STL 命名空间。

解释

结果

结果如下