1. 程式人生 > >OpenCV中findContours函式的使用

OpenCV中findContours函式的使用

從二值影象中找出物件的輪廓:

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 shape

4、獲得包圍物件的凸包
// 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()函式會改變影象