OpenCV如何在图像中寻找轮廓(60)

返回:OpenCV系列文章目录(持续更新中......)

上一篇:OpenCV如何模板匹配(59)
下一篇 :OpenCV检测凸包(61)

目标

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

cv::findContours 和 cv::drawContours 都是 OpenCV 库中常用的图像处理函数,主要用于图像分割和轮廓绘制等操作。

cv::findContours 是一个用于在二值图像中查找轮廓的函数。它可以根据二值图像中的像素灰度值(0 或非零)来确定对象的轮廓,并返回一个由所有轮廓点构成的向量。此外,findContours 还可以实现轮廓间的层次结构分析,进一步提高轮廓分析的精度。

cv::drawContours 则可以根据给定的轮廓向量,对指定的图像进行轮廓绘制操作。它可以绘制轮廓内部、轮廓外边界、轮廓及其外边界,也可以指定边界的颜色和宽度。通过 drawContours 函数,我们可以将轮廓绘制在原图像中,以便后续的图像分析和处理。

因此,cv::findContours 和 cv::drawContours 通常会一起使用。通过 findContours 函数查找轮廓,然后利用 drawContours 函数在原图像中绘制轮廓,可以更好地实现图像分割和轮廓分析等操作。

C++代码

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

cpp 复制代码
#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* );
 
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;
 }
 
 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;
}
 
void thresh_callback(int, void* )
{
 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 );
 }
 
 imshow( "Contours", drawing );
}

结果

在这里:


参考文献:

1、《Finding contours in your image》-----Ana Huamán

相关推荐
苏州邦恩精密3 分钟前
蔡司3D扫描仪厂家如何应用于新能源行业检测
人工智能·机器学习·3d·自动化·制造
黑不溜秋的16 分钟前
C++ STL 容器使用的底层数据结构
c++
灵晔君31 分钟前
【C++】标准模板库STL——set /multiset/map /multimap
开发语言·c++
阿里技术1 小时前
Agent 评测:方法论与体系设计
大数据·人工智能·算法
deephub1 小时前
用 Scikit-LLM 和 Groq 搭建情感分析 pipeline
人工智能·大语言模型·sklearn
赛联区块链1 小时前
工厂使用AI降本增效实践与探索
人工智能·ai智能体·deepseek·ai赋能·工业ai·工厂ai
千里马学框架1 小时前
google官方Perfetto 中使用 AI相关skill
android·人工智能·ai·framework·perfetto·性能·skill
蓝速科技1 小时前
蓝速科技 3D 全息舱 AI 数字人校园智慧升级实效展示
人工智能·科技·3d
观远数据1 小时前
像装应用一样落地BI:云市场模板如何降低行业分析项目的实施风险
人工智能
道可云1 小时前
淄博电机模具领军企业如何用AI提质增效?道可云携手精密制造专精特新,探索工业大脑赋能新路径
人工智能·制造