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

相关推荐
lizhihai_994 分钟前
股市学习心得-AI 产业链核心标的梳理清单
大数据·服务器·人工智能·科技·学习
暮雪倾风8 分钟前
【AI】国内使用Claude Code,配置Claude Code,使用DeepSeek为例
人工智能
FrameNotWork15 分钟前
HarmonyOS6.1 AI 模型管理架构设计与最佳实践
人工智能·harmonyos
没事别瞎琢磨19 分钟前
十、统一 Runner 入口——能力检测与模式回退
人工智能·node.js
装不满的克莱因瓶21 分钟前
了解 LangChain 中的 LLM 与 ChatModel 的差异
人工智能·python·ai·langchain·llm·agent·chatmodel
dingzd9524 分钟前
跨境社媒运营越到后面 越比拼账号的表达稳定性
大数据·人工智能·矩阵·内容营销
云烟成雨TD26 分钟前
Spring AI 1.x 系列【54】Retry 机制分析
java·人工智能·spring
没事别瞎琢磨28 分钟前
八、环境隔离——构建安全的子进程环境
人工智能·node.js
手写码匠28 分钟前
从零实现 Prompt 工程引擎:结构化提示、自动优化与多轮自省体系
人工智能·深度学习·算法·aigc
甲维斯31 分钟前
Claude Fable5首测,GPT5.5和国产模型弱爆了!
人工智能