首页 > 技术文章 > [opencv] 寻找凸包、外接矩形、最小包围矩形,最小外接圆

shanghai-achao 2016-02-26 10:13 原文

1、cvConvexHull2 寻找凸包

hull := cvConvexHull2 (ptseq, 0, CV_CLOCKWISE, 1);//ptseq,hull:pCvSeq;

//画出凸包点,并将凸包点用直线连接起来

ppoint:=cvGetSeqElem(hull,hull.total-1);//ppoint:pCvPoint;
p1.x:=ppoint.x;  //p1:TCvPoint;
p1.y:=ppoint.y;

for idx := 0 to hull.total-1 do
begin
ppoint:=cvGetSeqElem(hull,idx);
tempoint.x:=ppoint.x;//tempoint:Tcvpoint;
tempoint.y:=ppoint.y;
cvCircle(srcimage,tempoint,3,CV_RGB(255,255,255),3,8,0);
cvLine(srcimage,p1,tempoint,CV_RGB(255,255,255),3,8,0);
p1:=tempoint;
end;
cvShowImage('画出凸包',srcimage);
cvZero(srcimage);

//还可以直接用cvDrawContours将找到的凸包画出来

cvDrawContours(srcimage, hull, CV_RGB(255,255,255), CV_RGB(255, 255, 255), 0, -1, 8,cvPoint(0,0));//-1表示将凸包内部填充,取值1表示连接轮廓,连接线的宽度为1,取值2,3以此类推

 

2、cvBoundingRect 寻找外部矩形

rect:=cvBoundingRect(ptseq,1);//rect:TCvRect;ptseq:pCvSeq;
tempoint.x:=rect.x;//tempoint,p1:Tcvpoint;
tempoint.y:=rect.y;
p1.x:=rect.x+rect.width;
p1.y:=rect.y+rect.height;
cvRectangle(srcimage,tempoint,p1,CV_RGB(255,255,255),3,8,0);
cvShowImage('外部矩形',srcimage);
cvzero(srcimage);

 

3、cvMinAreaRect2 最小外接矩形

box2d:=cvCreateMemStorage ();//box2d: pCvMemStorage;
box:=cvMinAreaRect2(ptseq,box2d);//box:TCvBox2D;ptseq:pCvSeq;

cvBoxPoints(box,pt0,pt1,pt2,pt3);//cvBoxPoints为一个自定义函数,下面将贴出函数代码,pt0,pt1,pt2,pt3:Tcvpoint:

cvLine(srcimage,pt0,pt1,CV_RGB(255,255,255),3,8,0);
cvLine(srcimage,pt2,pt1,CV_RGB(255,255,255),3,8,0);
cvLine(srcimage,pt2,pt3,CV_RGB(255,255,255),3,8,0);
cvLine(srcimage,pt0,pt3,CV_RGB(255,255,255),3,8,0);
cvShowImage('最小外接矩形',srcimage);
cvzero(srcimage);

 

cvBoxPoints(MinAreaRectbox: TCvBox2D; var p0, p1, p2,p3: TCvPoint);//自定义函数的功能是根据TCvBox2D结构体中的参数,返回最小外接矩形的四个顶点

var
a,b:Single;

begin

a:=sin(MinAreaRectbox.angle*3.1415927/180)/2;
b:=cos(MinAreaRectbox.angle*3.1415927/180)/2;
p0.x:= round(MinAreaRectbox.center.x - a*MinAreaRectbox.size.height - b*MinAreaRectbox.size.width);
p0.y:= round(MinAreaRectbox.center.y + b*MinAreaRectbox.size.height - a*MinAreaRectbox.size.width);
p1.x:= round(MinAreaRectbox.center.x + a*MinAreaRectbox.size.height - b*MinAreaRectbox.size.width);
p1.y:= round(MinAreaRectbox.center.y - b*MinAreaRectbox.size.height - a*MinAreaRectbox.size.width);
p2.x:= round(2*MinAreaRectbox.center.x - p0.x);
p2.y:= round(2*MinAreaRectbox.center.y - p0.y);
p3.x:= round(2*MinAreaRectbox.center.x - p1.x);
p3.y:= round(2*MinAreaRectbox.center.y - p1.y);
end;

 

4、cvMinEnclosingCircle 最小外接圆

cvMinEnclosingCircle(ptseq,@center,@radius);//center:TCvPoint2D32f;radius:Single;ptseq:pCvSeq;

tempoint.x:=round(center.x);//tempoint:TCVpoint;
tempoint.y:=round(center.y);
cvCircle(srcimage,tempoint,Round(radius),CV_RGB(255,255,255),3,8,0);
cvShowImage('最小外接圆',srcimage);
cvzero(srcimage);

 

推荐阅读