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

相关推荐
emfuture4 分钟前
中嵌科技“岷山“实验室技术拆解:基于 DeepSeek-7B 的工控垂类模型,怎么把推理压到 50ms 以内?
人工智能·科技·lora·知识图谱·工业大模型·垂类微调·工控ai
阿里云大数据AI技术4 分钟前
Hologres 长记忆服务重磅发布,首月免费公测!
人工智能
大鱼>15 分钟前
AI+货物追踪:贵重物品智能追踪系统
人工智能·深度学习·算法·机器学习
大鱼>18 分钟前
AI+货物追踪:集装箱智能追踪系统
人工智能·深度学习·算法·机器学习
不穿铠甲的穿山甲27 分钟前
注意力机制
人工智能
雪隐27 分钟前
用Flutter做背单词APP-02我画了设计稿,然后让AI帮我设计了数据库(顺便聊了会天)
前端·人工智能·后端
love530love28 分钟前
CodexPro + MCP + Cloudflare 配置详解:HTTP2、QUIC 与连接排障
ide·人工智能·windows·ai agent
chh56330 分钟前
C++--string
java·开发语言·网络·c++·学习
Listen·Rain31 分钟前
向量化详解
java·人工智能·spring·机器学习·ai
keyanbanyungong39 分钟前
被市场忽略的AI4S细分赛道:MedPeer生物医药科研数字化稀缺龙头
大数据·人工智能