您的位置:首页 > 运维架构

Opencv2系列学习笔记10(提取连通区域轮廓)

2013-12-20 12:18 567 查看
连通区域指的是二值图像中相连像素组成的形状。而内、外轮廓的概念及opencv1中如何提取二值图像的轮廓见我的这篇博客:/article/1384069.html

轮廓的简单提取算法如下:

系统性地扫描图像直到遇到连通区域的一个点,以它为起始点,跟踪它的轮廓,标记边界上的像素。当轮廓完整闭合,扫描回到上一个位置,直到再次发现新的成分。

代码:

#include <iostream>
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>

using namespace std;
using namespace cv;

// 移除过小或过大的轮廓
void getSizeContours(vector<vector<Point>> &contours)
{
int cmin = 100;   // 最小轮廓长度
int cmax = 1000;   // 最大轮廓长度
vector<vector<Point>>::const_iterator itc = contours.begin();
while(itc != contours.end())
{
if((itc->size()) < cmin || (itc->size()) > cmax)
{
itc = contours.erase(itc);
}
else ++ itc;
}
}

// 计算连通区域的轮廓,即二值图像中相连像素的形状

int main()
{
Mat image = imread("E:\\opencv2cv\\lesson7\\Debug\\55.png",0);
if(!image.data)
{
cout << "Fail to load image" << endl;
return 0;
}
Mat imageShold;
threshold(image, imageShold, 100, 255, THRESH_BINARY);   // 必须进行二值化
vector<vector<Point>> contours;
//CV_CHAIN_APPROX_NONE  获取每个轮廓每个像素点
findContours(imageShold, contours, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE, cvPoint(0,0));
getSizeContours(contours);
cout << contours.size() << endl;
Mat result(image.size(), CV_8U, Scalar(255));
drawContours(result, contours, -1, Scalar(0), 2);   // -1 表示所有轮廓
namedWindow("result");
imshow("result", result);
namedWindow("image");
imshow("image", image);
waitKey(0);
return 0;
}


结果:

未移除过大多小的轮廓前:



移除后:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: