1. 程式人生 > >7.6提取區域的輪廓,計算區域的形狀描述運算元

7.6提取區域的輪廓,計算區域的形狀描述運算元

#include"opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
using namespace cv;
void main()
{
	Mat img=imread("C:\\Users\\Administrator\\Desktop\\工作\\testp\\shuiniu.jpg",0);
	//Mat img1=imread("C:\\Users\\Administrator\\Desktop\\工作\\testp\\group.jpg",0);
	//Mat img=imread("C:\\Users\\Administrator\\Desktop\\工作\\testp\\121.jpg");
	/*threshold(img,img,230,255,THRESH_BINARY);
	imwrite("shuiniu.jpg",img);
	imshow("1",img);
	waitKey(0);*/
	vector<vector<Point>>contours;
	findContours(img,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);
	Mat result(img.size(),CV_8U,Scalar(255));
	//drawContours(result,contours,-1,0,2);

	int cmin=50;
	int cmax=1000;
	vector<vector<Point>>::iterator itc=contours.begin();
	while (itc!=contours.end())
	{
		if (itc->size()<cmin||itc->size()>cmax)
		{
			itc=contours.erase(itc);
		}
		else
			++itc;
	}

	Rect r0=boundingRect(contours[0]);
	rectangle(result,r0,0,2);
	float radius;
	Point2f center;
	minEnclosingCircle(contours[1],center,radius);
	circle(result,center,static_cast<int>(radius),Scalar(0),2);
	vector<Point>poly;
	approxPolyDP(contours[2],poly,5,true);
	polylines(result,poly,true,0,2);
	vector<Point>hull;
	convexHull(contours[3],hull);
	polylines(result,hull,true,0,2);
	
	itc=contours.begin();
	while (itc!=contours.end())
	{
	   Moments mom=moments(Mat (*itc++));
	   circle(result,Point(mom.m10/mom.m00,mom.m01/mom.m00),2,Scalar(0),2);

	}

	drawContours(result,contours,-1,0,2);

	imshow("src",img);
	imshow("result",result);
	waitKey(0);

}
<img src="https://img-blog.csdn.net/20160412171810334?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />