OpenCV实现最小外接正矩形
本文实例为大家分享了OpenCV实现最小外接正矩形的具体代码,供大家参考,具体内容如下
#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
#include "cxcore.h"
#include "math.h"
#include <iostream.h>
int main(int argc, char* argv[])
{
IplImage *src;
IplImage *dst;
IplImage *ROI;
CvMemStorage* storage=cvCreateMemStorage(0);
CvSeq* contour=0;
src=cvLoadImage("I:\\test.jpg",0);
cvNamedWindow("image0",1);
cvShowImage("image0",src);
int hei=src->height;
int wid=src->width;
uchar *data;
data=(uchar*)src->imageData;
int widstep=src->widthStep;
int channel=src->nChannels;
dst=cvCreateImage(cvSize(wid,hei),IPL_DEPTH_8U,3);
ROI=cvCreateImage(cvSize(wid,hei),IPL_DEPTH_8U,3);
for (int i=0;i<hei;i++)
{
for(int j=0;j<wid;j++)
{
if (data[i*widstep+j*channel]>120)
{
data[i*widstep+j*channel]=0;
}
else
{
data[i*widstep+j*channel]=255;
}
}
}
cvNamedWindow("image",0);
cvShowImage("image",src);
printf("图像的高为:%d,宽为:%d\n\n",hei,wid);
cvCvtColor(src, dst, CV_GRAY2BGR);;
cvFindContours(src,storage,&contour,sizeof(CvContour),CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE);
for(;contour!=0;contour=contour->h_next)
{
double length =cvArcLength(contour);
double area =fabs(cvContourArea(contour));
CvRect rect = cvBoundingRect(contour,1);
cout<<"Length="<<length<<" Area="<<area<<endl;
CvPoint p1;
CvPoint p2;
p1.x=rect.x;
p1.y=rect.y;
p2.x=rect.x+rect.width;
p2.y=rect.y+rect.height;
cout<<"p1=("<<p1.x<<","<<p1.y<<")";
cout<<"p2=("<<p2.x<<","<<p2.y<<")"<<endl;
cvRectangle(dst,p1,p2,CV_RGB(255,0,0),1,8,0);
}
cvNamedWindow("dst",1);
cvShowImage("dst",dst);
cvWaitKey(0);
return 0;
}
原图:
二值化反色图:
最小正矩形图:
最小正矩形信息:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
以上是 OpenCV实现最小外接正矩形 的全部内容, 来源链接: utcz.com/p/245362.html