Opencv中通过使用findContours函数,简单几个的步骤就可以检测出物体的轮廓,很方便。这些准备继续探讨一下
findContours方法中各参数的含义及用法,比如要求只检测最外层轮廓该怎么办?contours里边的数据结构是怎样
的?hierarchy到底是什么鬼?Point()有什么用?
先从findContours函数原型看起:
findContours( InputOutputArray image, OutputArrayOfArrays contours,
OutputArray hierarchy, int mode,
int method, Point offset=Point());
第一个参数:image,单通道图像矩阵,可以是灰度图,但更常用的是二值图像,一般是经过Canny、拉普拉斯等边
缘检测算子处理过的二值图像;
第二个参数:contours,定义为“vector
#include "core/core.hpp"
#include "highgui/highgui.hpp"
#include "imgproc/imgproc.hpp"
#include "iostream"
using namespace std;
using namespace cv;
int main(int argc,char *argv[])
{
Mat imageSource=imread(argv[1],0);
imshow("Source Image",imageSource);
Mat image;
GaussianBlur(imageSource,image,Size(3,3),0);
Canny(image,image,100,250);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(image,contours,hierarchy,RETR_TREE,CHAIN_APPROX_SIMPLE,Point());
Mat imageContours=Mat::zeros(image.size(),CV_8UC1);
Mat Contours=Mat::zeros(image.size(),CV_8UC1); //绘制
for(int i=0;i<contours.size();i++)
{
//contours[i]代表的是第i个轮廓,contours[i].size()代表的是第i个轮廓上所有的像素点数
for(int j=0;j<contours[i].size();j++)
{
//绘制出contours向量内所有的像素点
Point P=Point(contours[i][j].x,contours[i][j].y);
Contours.at<uchar>(P)=255;
}
//输出hierarchy向量内容
char ch[256];
sprintf(ch,"%d",i);
string str=ch;
cout<<"向量hierarchy的第" <<str<<" 个元素内容为:"<<endl<<hierarchy[i]<<endl<<endl;
//绘制轮廓
drawContours(imageContours,contours,i,Scalar(255),1,8,hierarchy);
}
imshow("Contours Image",imageContours); //轮廓
imshow("Point of Contours",Contours); //向量contours内保存的所有轮廓点集
waitKey(0);
return 0;
}