从二值图像中找出对象的轮廓:
OpenCV中函数findContours()用于中对象的轮廓,有两种形式:
第一种:
void findContours( InputOutputArray image, OutputArrayOfArrays contours,
int mode, int method, Point offset=Point());
第二种:
void findContours( InputOutputArray image, OutputArrayOfArrays contours,
OutputArray hierarchy, int mode,
int method, Point offset=Point());
参数:
contours:是找到的各个轮廓
mode :CV_RETR_EXTERNAL找到的轮廓里面没有小轮廓(洞),CV_RETR_LIST找到的轮廓中可以包括小轮廓
hierarchy:层次结构,存放了轮廓同一等级的前后轮廓的索引,不同等级的父亲轮廓和孩子轮廓的索引
method:CV_CHAIN_APPROX_NONE获取轮廓上所有像素点
代码:运行环境(VS2012 + OpenCV2.4)
#include "highgui.h"
#include "imgproc/imgproc.hpp"
int main()
{
cv::Mat image = cv::imread("D:/Development/OpenCV/images/binaryGroup.bmp" , 0) ;
std::vector<std::vector<cv::Point>> contours ;
//获取轮廓不包括轮廓内的轮廓
cv::findContours(image , contours ,
CV_RETR_EXTERNAL , CV_CHAIN_APPROX_NONE) ;
cv::Mat result(image.size() , CV_8U , cv::Scalar(255)) ;
cv::drawContours(result , contours ,
-1 , cv::Scalar(0) , 2) ;
cv::imshow("resultImage" , result) ;
//获取所有轮廓包括轮廓内的轮廓
std::vector<std::vector<cv::Point>> allContours ;
cv::Mat allContoursResult(image.size() , CV_8U , cv::Scalar(255)) ;
cv::findContours(image , allContours ,
CV_RETR_LIST , CV_CHAIN_APPROX_NONE) ;
cv::drawContours(allContoursResult , allContours ,-1 ,
cv::Scalar(0) , 2) ;
cv::imshow("allContours" , allContoursResult) ;
//获取轮廓的等级
std::vector<cv::Vec4i> hierarchy ;
cv::findContours(image , contours , hierarchy , CV_RETR_TREE ,
CV_CHAIN_APPROX_NONE) ;
cv::waitKey(0) ;
return 0 ;
1、获取包围对象的垂直矩阵
cv::Rect r0= cv::boundingRect(cv::Mat(contours[0]));
cv::rectangle(result,r0,cv::Scalar(0),2);2、获取包围对象的最小圆
cv::Rect r0= cv::boundingRect(cv::Mat(contours[0]));
cv::rectangle(result,r0,cv::Scalar(0),2);3、获取包围对象的多边形
// testing the approximate polygon
std::vector<cv::Point> poly;
cv::approxPolyDP(cv::Mat(contours[2]),poly,
5, // accuracy of the approximation
true); // yes it is a closed shape4、获得包围对象的凸包
// testing the convex hull
std::vector<cv::Point> hull;
cv::convexHull(cv::Mat(contours[3]),hull);5、获取各个对象的质心
itc= contours.begin();
while (itc!=contours.end()) {
// compute all moments
cv::Moments mom= cv::moments(cv::Mat(*itc++));
// draw mass center
cv::circle(result,
// position of mass center converted to integer
cv::Point(mom.m10/mom.m00,mom.m01/mom.m00),
2,cv::Scalar(0),2); // draw black dot
}注意:findContours()函数会改变图像
本文介绍了OpenCV中的findContours函数,用于从二值图像中提取对象的轮廓。函数有两种形式,并详细解析了参数mode和method的含义。通过示例代码展示了在VS2012和OpenCV2.4环境下如何使用该函数获取轮廓。
1万+

被折叠的 条评论
为什么被折叠?



