opencv中使用形状包围轮廓

外部矩形边界 C++ Rect boundingRect(InputArray points)

最小包围矩形:C++ RotatedRect minAreaRect(InputArray points)
最小包围圆形:C++ void minEnclosingCircle(InputArrayPoints,Point2f&center,float&radius)
椭圆拟合:C++ RotatedRect fitEllipse(InputArray points)
逼近多边形:C++ void approxPolyDP(InputArray curve,OutputArray approxCurve,double epsilon,bool closed);
curve是vector或者Mat的点集
approx输出类型和输入一样
epsilon是近似曲线和原始曲线的最大间隔
closed是指曲线是否闭合
例子一:
用最小包围矩形包住随机生成的点,在讲之前,先讲一下RotatedRect这个返回类型,是旋转矩形
要将这个返回类型,变到Mat里面,方法是:将其四角存到(Point  数组名) 里面,变成一个轮廓
RotatedRect::RotatedRect(const Point2f& center, const Size2f& size, float angle)// 中心点(不是左上角坐标),尺寸,旋转角度

RotatedRect rRect = RotatedRect(Point2f(100,100), Size2f(100,50), 30);

int main()
{
	Mat src;
	src=Mat::zeros(600,600,CV_8UC3); //创建一个画布
	RNG rng;
	vector points;
	for(int i=0;i<20;i++)
	{
		Point2f point;
		point.x=rng.uniform(src.cols*0.4,src.cols*0.7);
		point.y=rng.uniform(src.rows*0.5,src.rows*0.7);
		points.push_back(point);
		circle(src,point,3,Scalar(255,255,255),CV_FILLED,8,0);//顺便把圆画出来
	}
	RotatedRect box=minAreaRect(points);  //提取RotatedRect需要用以下方法,存四角
	Point2f four_cornor[4];
	box.points(four_cornor);
	    for(int i=0;i<4;i++)  //把RotatedRect画出来
		{
			line(src,four_cornor[i],four_cornor[(1+i)%4],Scalar(255,255,255),1,8,0);
		}
	imshow("a",src);
	waitKey(0);
}

例子二:用圆包围

int main()
{
	Mat src;
	src=Mat::zeros(600,600,CV_8UC3); //创建一个画布
	RNG rng;
	vector points;
	for(int i=0;i<50;i++)
	{
		Point2f point;
		point.x=rng.uniform(src.cols*0.4,src.cols*0.7);
		point.y=rng.uniform(src.rows*0.5,src.rows*0.7);
		points.push_back(point);
		circle(src,point,3,Scalar(255,255,255),CV_FILLED,8,0);//顺便把圆画出来
	}
	Point2f center;
	float radiu;
	minEnclosingCircle(points,center,radiu);  
	//把圆画出来
		circle(src,center,radiu,Scalar(255,255,255),1,8,0);
	imshow("a",src);
	waitKey(0);
}


例子三:使用多边形包围真实图像的轮廓

#include
#include 
#include 
#include 
#include 
#include 
#include  "vector"

using namespace std;
using namespace cv;

//目的:找到一个图像的轮廓,并用多边形逼近,且可以用进度条调整阈值化函数
//步骤:1.读入一张图,同时灰度化 2.阈值化 3.findCounters 4.多边形逼近函数 5.可视化 

Mat src,dst;
int s_threshold=80;
void thresCallback(int,void*);

int main()
{
	src=imread("zuqiuchang.jpg",0);
	
	namedWindow("a");
	createTrackbar("阈值","a",&s_threshold,255,thresCallback);
	thresCallback(s_threshold,0);

	waitKey(0);

}

void thresCallback(int,void*)
{
	Mat result;
	threshold(src,dst,s_threshold,255,THRESH_BINARY);
	vector> contour;
	vector hierarchy;
	result.create(dst.size(),CV_8UC3);//创建一个最后接受结果用的Mat

	findContours(dst,contour,hierarchy,RETR_CCOMP,CHAIN_APPROX_SIMPLE);
	//这里轮廓应该有很多个,还是要有一个循环遍历

	vector> contour_result(contour.size());  
	vector center(contour.size());
	vector   radius (contour.size());
	vector rect(contour.size());
 
	for(int i=0;i

原图:

结果:



展开阅读全文

没有更多推荐了,返回首页