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

相关推荐
静心问道7 分钟前
TrOCR: 基于Transformer的光学字符识别方法,使用预训练模型
人工智能·深度学习·transformer·多模态
说私域9 分钟前
基于开源AI大模型、AI智能名片与S2B2C商城小程序源码的用户价值引导与核心用户沉淀策略研究
人工智能·开源
亲持红叶11 分钟前
GLU 变种:ReGLU 、 GEGLU 、 SwiGLU
人工智能·深度学习·神经网络·激活函数
说私域11 分钟前
线上协同办公时代:以开源AI大模型等工具培养网感,拥抱职业变革
人工智能·开源
群联云防护小杜12 分钟前
深度隐匿源IP:高防+群联AI云防护防绕过实战
运维·服务器·前端·网络·人工智能·网络协议·tcp/ip
摘星编程18 分钟前
构建智能客服Agent:从需求分析到生产部署
人工智能·需求分析·智能客服·agent开发·生产部署
不爱学习的YY酱21 分钟前
信息检索革命:Perplexica+cpolar打造你的专属智能搜索中枢
人工智能
whaosoft-1432 小时前
51c自动驾驶~合集7
人工智能
刘晓倩5 小时前
Coze智能体开发实战-多Agent综合实战
人工智能·coze
石迹耿千秋6 小时前
迁移学习--基于torchvision中VGG16模型的实战
人工智能·pytorch·机器学习·迁移学习