什么是轮廓?

轮廓是一系列相连的点组成的曲线,代表了物体的基本外形。

轮廓与边缘好像挺像的?

是的,确实挺像,那么区别是什么呢?简而言之,轮廓是连续的,而边缘并不全都连续(见下图示例)。其实边缘主要是作为图像的特征使用,比如可以用边缘特征可以区分脸和手,而轮廓主要用来分析物体的形态,比如物体的周长和面积等,可以说边缘包括轮廓。

边缘和轮廓的区别(图片来源:http://pic.ex2tron.top/cv2_understand_contours.jpg

寻找轮廓的操作一般用于二值化图,所以通常会使用阈值分割或Canny边缘检测先得到二值图。

【注:寻找轮廓是针对白色物体的,一定要保证物体是白色,而背景是黑色,不然很多人在寻找轮廓时会找到图片最外面的一个框】

OpenCV4.1.0 C++ Sample Code:

/**
* @function findContours_Demo.cpp
* @brief Demo code to find contours in an image
* @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); /// Function header
void thresh_callback(int, void* ); /**
* @function main
*/
int main( int argc, char** argv )
{
/// Load source image
CommandLineParser parser( argc, argv, "{@input | ../data/HappyFish.jpg | input image}" );
Mat src = imread( 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) ); /// Create Window
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* )
{
/// Detect edges using Canny
Mat canny_output;
Canny( src_gray, canny_output, thresh, thresh*2 ); /// Find contours
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE ); /// Draw contours
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 );
}

Result:

应用1:寻找正方形(squares.cpp)

// The "Square Detector" program.
// It loads several images sequentially and tries to find squares in
// each image #include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/core/utils/filesystem.hpp" #include <iostream> using namespace cv;
using namespace std; static void help(const char* programName)
{
cout <<
"\nA program using pyramid scaling, Canny, contours and contour simplification\n"
"to find squares in a list of images (pic1-6.png)\n"
"Returns sequence of squares detected on the image.\n"
"Call:\n"
"./" << programName << " [file_name (optional)]\n"
"Using OpenCV version " << CV_VERSION << "\n" << endl;
} int thresh = 50, N = 11;
const char* wndname = "Square Detection Demo"; // helper function:
// finds a cosine of angle between vectors
// from pt0->pt1 and from pt0->pt2
static double angle( Point pt1, Point pt2, Point pt0 )
{
double dx1 = pt1.x - pt0.x;
double dy1 = pt1.y - pt0.y;
double dx2 = pt2.x - pt0.x;
double dy2 = pt2.y - pt0.y;
return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
} // returns sequence of squares detected on the image.
static void findSquares( const Mat& image, vector<vector<Point> >& squares )
{
squares.clear(); Mat pyr, timg, gray0(image.size(), CV_8U), gray; // down-scale and upscale the image to filter out the noise
pyrDown(image, pyr, Size(image.cols/2, image.rows/2));
pyrUp(pyr, timg, image.size());
vector<vector<Point> > contours; // find squares in every color plane of the image
for( int c = 0; c < 3; c++ )
{
int ch[] = {c, 0};
mixChannels(&timg, 1, &gray0, 1, ch, 1); // try several threshold levels
for( int l = 0; l < N; l++ )
{
// hack: use Canny instead of zero threshold level.
// Canny helps to catch squares with gradient shading
if( l == 0 )
{
// apply Canny. Take the upper threshold from slider
// and set the lower to 0 (which forces edges merging)
Canny(gray0, gray, 0, thresh, 5);
// dilate canny output to remove potential
// holes between edge segments
dilate(gray, gray, Mat(), Point(-1,-1));
}
else
{
// apply threshold if l!=0:
// tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
gray = gray0 >= (l+1)*255/N;
} // find contours and store them all as a list
findContours(gray, contours, RETR_LIST, CHAIN_APPROX_SIMPLE); vector<Point> approx; // test each contour
for( size_t i = 0; i < contours.size(); i++ )
{
// approximate contour with accuracy proportional
// to the contour perimeter
approxPolyDP(contours[i], approx, arcLength(contours[i], true)*0.02, true); // square contours should have 4 vertices after approximation
// relatively large area (to filter out noisy contours)
// and be convex.
// Note: absolute value of an area is used because
// area may be positive or negative - in accordance with the
// contour orientation
if( approx.size() == 4 &&
fabs(contourArea(approx)) > 1000 &&
isContourConvex(approx) )
{
double maxCosine = 0; for( int j = 2; j < 5; j++ )
{
// find the maximum cosine of the angle between joint edges
double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
maxCosine = MAX(maxCosine, cosine);
} // if cosines of all angles are small
// (all angles are ~90 degree) then write quandrange
// vertices to resultant sequence
if( maxCosine < 0.3 )
squares.push_back(approx);
}
}
}
}
} // the function draws all the squares in the image
static void drawSquares( Mat& image, const vector<vector<Point> >& squares )
{
for( size_t i = 0; i < squares.size(); i++ )
{
const Point* p = &squares[i][0];
int n = (int)squares[i].size();
polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, LINE_AA);
} imshow(wndname, image);
} String absoluteFilePath(const String& relative_path) {
String root_path = "F:/opencv/build/bin/sample-data/";
String path = utils::fs::join(root_path, relative_path);
return path;
} int main(int argc, char** argv)
{
static const char* names[] = { "pic1.png", "pic2.png", "pic3.png",
"pic4.png", "pic5.png", "pic6.png", 0 };
help(names[0]); vector<vector<Point> > squares; for( int i = 0; names[i] != 0; i++ )
{
string filename = absoluteFilePath(names[i]);
Mat image = imread(filename, IMREAD_COLOR);
if( image.empty() )
{
cout << "Couldn't load " << filename << endl;
continue;
} findSquares(image, squares);
drawSquares(image, squares); int c = waitKey();
if( c == 27 )
break;
} return 0;
}

结果:

  

  

推荐:

OpenCV 对轮廓的绘图与筛选操作总结

基于OpenCV的形状检测

【计算机视觉】OpenCV篇(9) - 轮廓(寻找/绘制轮廓)的更多相关文章

  1. opencv —— minEnclosingCircle、fitEllipse 寻找包裹轮廓的最小圆、点集拟合椭圆

    寻找包裹轮廓的最小圆:minEnclosingCircle 函数 返回圆应满足:① 轮廓上的点均在圆形空间内.② 没有面积更小的满足条件的圆. void minEnclosingCircle(Inpu ...

  2. opencv —— boundingRect、minAreaRect 寻找包裹轮廓的最小正矩形、最小斜矩形

    寻找包裹轮廓的最小正矩形:boundingRect 函数 返回矩阵应满足:① 轮廓上的点均在矩阵空间内.② 矩阵是正矩阵(矩形的边界与图像边界平行). Rect boundingRect(InputA ...

  3. OpenCV计算机视觉学习(8)——图像轮廓处理(轮廓绘制,轮廓检索,轮廓填充,轮廓近似)

    如果需要处理的原图及代码,请移步小编的GitHub地址 传送门:请点击我 如果点击有误:https://github.com/LeBron-Jian/ComputerVisionPractice 1, ...

  4. opencv 6 图像轮廓与图像分割修复 1 查找并绘制轮廓 寻找物体的凸包

    查找并绘制轮廓 寻找轮廓(findContours)函数 绘制轮廓(drawContours()函数) 基础实例程序:轮廓查找 #include <opencv2/opencv.hpp> ...

  5. opencv —— findContours、drawContours 寻找并绘制轮廓

    轮廓图像与 Canny 图像的区别 一个轮廓一般对应一系列的点,也就是图像中的一条曲线.轮廓图像和 Canny 图像乍看起来表现几乎是一致的,但其实组成两者的数据结构差别很大: Canny 边缘图像是 ...

  6. 查找并绘制轮廓[OpenCV 笔记XX]

    好久没有更新了,原谅自己放了个假最近又在赶进度,所以...更新的内容是很靠后的第八章,因为最近工作要用就先跳了,后面会更新笔记编号...加油加油! 在二值图像中寻找轮廓 void cv::findCo ...

  7. 【OpenCV函数】轮廓提取;轮廓绘制;轮廓面积;外接矩形

    FindContours 在二值图像中寻找轮廓  int cvFindContours( CvArr* image, CvMemStorage* storage, CvSeq** first_cont ...

  8. 查找并绘制轮廓 opencv

    findContours(): 第二个参数为一个检测到的轮廓,函数调用后的运算结果都放在这里,每个轮廓存储为1个点向量,用point类型的vector表示. 第三个参数表示轮廓数量,包含了许多元素.每 ...

  9. opencv::轮廓周围绘制矩形框和圆形框

    基于RDP算法实现,目的是减少多边形轮廓点数 approxPolyDP(InputArray curve, OutputArray approxCurve, double epsilon, bool ...

随机推荐

  1. 集成腾讯Bugly日志- Android(1)

    Bugly 是腾讯公司为移动开发者开放的服务之一,这里主要指 Crash 监控.崩溃分析等质量跟踪服务. 一.登录BUGLY官网 1.登录BUGLY官网以后,选择新建产品,选择IOS或ADNROID平 ...

  2. NISP二级笔记(二) 信息安全管理体系

  3. PHP安装之configure的配置参数

    1.生成环境安装配置如下 要求安装如下库: imagickgdmysqlmysqlimysqlndphalconPharsoapsocketsxwebxsvczipzlib 具体查看 vim php- ...

  4. Shell脚本之sed的使用

    1.sed命令:主要作用是查找:新增 删除 和修改替换. user.txt daokr#cat user.txt ID Name Sex Age zhang M wang G cheng M huah ...

  5. 【转】浅析Linux中的零拷贝技术

    本文探讨Linux中主要的几种零拷贝技术以及零拷贝技术适用的场景.为了迅速建立起零拷贝的概念,我们拿一个常用的场景进行引入: 引文## 在写一个服务端程序时(Web Server或者文件服务器),文件 ...

  6. Java 基础:单例模式 Singleton Pattern

    1.简介 单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一.这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式. 这种模式涉及到一个单一的类,该类负责创 ...

  7. C语言JSON序列化/反序列化

    最近想找一个C语言处理嵌套结构体和结构体数组的json库,理想的是能够很容易处理复杂结构体嵌套,并且使用简单的,但是没找到比较合适的,于是打算自己封装一个: 两个问题: C语言结构体本身没有元数据,这 ...

  8. Java学习个人备忘录之入门基础

    临时配置环境方式:查看path下的环境变量 set path修改path下的环境变量 set path=haha删除path下的环境变量 set path=查看当前java的版本 javac -ver ...

  9. Windows和Linux下putenv()函数导致composer更新失败

    bug复现: 原因: putenv() 函数设置特定的环境变量有可能是一个潜在的安全漏洞,所以这个函数在php配置文件中是默认禁止的,在 php.ini 中查找此函数,然后将此函数删除掉,重载配置即可 ...

  10. Python 23种设计模式全(python例子)

    从今年5月份开始打算把设计模式都写到博客里,持续到现在总算是写完了.写的很慢,好歹算是有始有终.对这些设计模式有些理解的不准确,有些甚至可能是错的,请看到的同学拍砖留言.内容来源很杂,大部分参考或者摘 ...