1、轮廓检测
轮廓检测是从灰度图中检索物体的轮廓线。即提取边缘线。
openCV提供两个函数findContours 和 drawContours。
(1)findContours()函数
void findContours(
InputOutputArray image,
OutputArrayOfArrays contours, // 检测出的轮廓对象
OutputArray hierarchy, // 检测图像的拓扑结构
int mode, // 检测模式
int method, // 检测方法
Point offset = Point()
);
int mode:
RETR_EXTERNAL,// 只检测最外圈的轮廓
RETR_LIST,// 检测出所有轮廓,但检测它们的关系
RETR_CCOMP,// 检测出所有轮廓,将它们组织成二层的层次结构
RETR_TREE,// 检测出所有轮廓,嵌套建立它们之间的关系。
int method:
CHAIN_APPROX_NONE:保存所有轮廓点。
CHAIN_APPROX_SIMPLE:压缩水垂直对角线,只保留线的两端点
CHAIN_APPROX_TC89_L1 :使用teh-Chinl chain 近似算法
CHAIN_APPROX_TC89_KCOS:使用teh-Chinl chain 近似算法
2、代码
Mat cannyMat;
vector<vector<Point>> ptContours;
vector<Vec4i> hierarchy;
Canny(srcImg1, cannyMat, 100, 200);
contourMethod = contourMethod == 0 ? 1 : contourMethod;
findContours(cannyMat, ptContours, hierarchy, contourMode, contourMethod,Point(0,0));
Mat dest;
srcImg1.copyTo(dest);
char* method_name[] =
{
"CHAIN_APPROX_NONE",
"CHAIN_APPROX_SIMPLE",
"CHAIN_APPROX_TC89_L1",
"CHAIN_APPROX_TC89_KCOS",
};
char* mode_name[] =
{
"RETR_EXTERNAL",
"RETR_LIST",
"RETR_CCOMP",
"RETR_TREE",
"RETR_FLOODFILL",
};
int lineWidth = 2;
for (int i = 0; i < ptContours.size(); i++)
{
putText(dest,
method_name[contourMethod-1],
Point(20, 40),
1,
1.0,
Scalar(255, 255, 255),
2
);
putText(dest,
mode_name[contourMode],
Point(20, 60),
1,
1.0,
Scalar(255, 255, 255),
2
);
drawContours(dest,
ptContours,
i,
Scalar(0, 255, 0),
lineWidth
);
}
imshow("Contours", dest);
3、工程项目源码下载
本文源码在Debug–x64下编译运行
ZIP包中包含开发环境,下载解压即可直接编译运行。