Goal
在本教程中,您将学习如何:
使用 OpenCV 函数 cv::findContours
使用 OpenCV 函数 cv::drawContours
Theory
Code
本教程代码如下所示。 你也可以从这里下载opencv/findContours_demo.cpp at 4.x · opencv/opencv (github.com)
/**
* @function findContours_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 main
*/
int main( int argc, char** argv )
{
/// 加载源图像
CommandLineParser parser( argc, argv, "{@input | HappyFish.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;
}
///将图像转换为灰色并模糊它 Convert image to gray and blur it
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 检测边缘 Detect edges using Canny
Mat canny_output;
Canny( src_gray, canny_output, thresh, thresh*2 );
///寻找轮廓
vector<vector<Point> > contours;//轮廓点 向量
vector<Vec4i> hierarchy;
findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE );
/// 绘制轮廓
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, 2, LINE_8, hierarchy, 0 );//黑色背景上绘制所有轮廓
}
///在窗口显示 Show in a window
imshow( "Contours", drawing );
}
Explanation
Result


559

被折叠的 条评论
为什么被折叠?



