#include "stdafx.h"
#include <iostream>
#include<string>
#include <stdio.h>
#include <cv.h>
#include <highgui.h>
#include <cxcore.h>
#include <stdio.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
IplImage* src=cvLoadImage("3.jpg",0);
IplImage* des=cvCreateImage(cvGetSize(src),src->depth,src->nChannels);
cvZero(des);
cvThreshold(src,src,0,150,CV_THRESH_BINARY);
CvMemStorage* memory=cvCreateMemStorage(0);
CvSeq* Icontour=NULL;
CvSeq* maxContour =NULL;
cvShowImage("原始图像1",src);
cvFindContours(src,memory,&Icontour, sizeof(CvContour),CV_RETR_LIST,CV_CHAIN_APPROX_SIMPLE,cvPoint(0,0));
double area=0;
double maxArea=0;
while(Icontour)
{
area=fabs(cvContourArea(Icontour,CV_WHOLE_SEQ));
cvDrawContours(src, Icontour,
CV_RGB(255,255,255), CV_RGB(255, 255,255),
0, 1, 8, cvPoint(0,0));
if(area>200 && area<400)
{
maxContour = Icontour;
}
Icontour =Icontour->h_next;
}
cvDrawContours(des, maxContour,
CV_RGB(255,255,255), CV_RGB(255, 255,255), 0, 1, 8, cvPoint(0,0));
//CvRect rect=cvBoundingRect(maxContour,0);
CvBox2D box=cvMinAreaRect2(maxContour);
cout<<"长度: "<<box.size.width<<endl<<"宽度: "<<box.size.height;
//cvRectangle(src,cvPoint((rect.x-rect.height/2),(rect.y-rect.width/2)),cvPoint((rect.x+rect.height/2),(rect.y+rect.width/2)),cvScalar(255,255,255),1,8,0);
// cvRectangle(src,cvPoint((rect.x-rect.height/2),(rect.y-rect.width/2)),cvPoint((rect.x-rect.height/2),(rect.y-rect.width/2)),cvScalar(255,255,255),2,8,0);
// cvDrawCircle(src,cvPoint(box.center.x,box.center.y),box.size.height,cvScalar(255,255,255),2,8,0);
CvPoint2D32f p4[4];
cvBoxPoints(box,p4);
cvLine(des, cvPoint(cvRound(p4[0].x), cvRound(p4[0].y)),
cvPoint(cvRound(p4[1].x), cvRound(p4[1].y)), CV_RGB(0, 0, 255),2);
cvLine(des, cvPoint(cvRound(p4[1].x), cvRound(p4[1].y)),
cvPoint(cvRound(p4[2].x), cvRound(p4[2].y)), CV_RGB(0, 0, 255),2);
cvLine(des, cvPoint(cvRound(p4[3].x), cvRound(p4[3].y)),
cvPoint(cvRound(p4[2].x), cvRound(p4[2].y)), CV_RGB(0,0, 255),2);
cvLine(des, cvPoint(cvRound(p4[3].x), cvRound(p4[3].y)),
cvPoint(cvRound(p4[0].x), cvRound(p4[0].y)), CV_RGB(0, 0,255),2);
cvShowImage("原始图像",src);
cvShowImage("保留最大值",des);
cvWaitKey(0);
//cvReleaseImage(&src);
cvDestroyWindow("原始图像");
return 0;
}