findContours函数,这个函数的原型为
void findContours( InputOutputArray image, OutputArrayOfArrays contours,
int mode, int method, Point offset=Point());
参数说明
image:输入图像
image必须为一个2值单通道图像
contours:检测的轮廓数组
每一个轮廓用一个point类型的vector表示
hiararchy:参数和轮廓个数相同
每个轮廓contours[ i ]对应4个hierarchy元素hierarchy[ i ][ 0 ] ~hierarchy[ i ][ 3 ],分别表示后一个轮廓、前一个轮廓、父轮廓、内嵌轮廓的索引编号,如果没有对应项,该值设置为负数。
mode:表示轮廓的检索模式
CV_RETR_EXTERNAL表示只检测外轮廓
CV_RETR_LIST检测的轮廓不建立等级关系
CV_RETR_CCOMP建立两个等级的轮廓,上面的一层为外边界,里面的一层为内孔的边界信息。如果内孔内还有一个连通物体,这个物体的边界也在顶层。
CV_RETR_TREE建立一个等级树结构的轮廓。具体参考contours.c这个demo
method:轮廓的近似办法
CV_CHAIN_APPROX_NONE存储所有的轮廓点,相邻的两个点的像素位置差不超过1,即max(abs(x1-x2),abs(y2-y1))==1
CV_CHAIN_APPROX_SIMPLE压缩水平方向,垂直方向,对角线方向的元素,只保留该方向的终点坐标,例如一个矩形轮廓只需4个点来保存轮廓信息
CV_CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_KCOS使用teh-Chinl chain 近似算法
offset表示代表轮廓点的偏移量,可以设置为任意值。
对ROI图像中找出的轮廓,并要在整个图像中进行分析时,这个参数还是很有用的。
例子:
#include <iostream>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
int main()
{
// Read input binary image
Mat image= imread("./binaryGroup.bmp",0);
if (!image.data)
return 0;
namedWindow("Binary Image");
imshow("Binary Image",image);
// Get the contours of the connected components
vector<vector<Point>> contours;
//findContours的输入是二值图像
findContours(image,
contours, // a vector of contours
CV_RETR_EXTERNAL, // retrieve the external contours
CV_CHAIN_APPROX_NONE); // retrieve all pixels of each contours
// Print contours' length轮廓的个数
cout << "Contours: " << contours.size() << endl;
vector<vector<Point>>::const_iterator itContours= contours.begin();
for ( ; itContours!=contours.end(); ++itContours) {
cout << "Size: " << itContours->size() << endl;//每个轮廓包含的点数
}
// draw black contours on white image
Mat result(image.size(),CV_8U,Scalar(0));
drawContours(result,contours, //画出轮廓
-1, // draw all contours
Scalar(255), // in black
2); // with a thickness of 2
namedWindow("Contours");
imshow("Contours",result);
waitKey();
return 0;
}