1. 程式人生 > >opencv 顯示最小面積的外接矩形,並求該矩形的長和寬以及四個角的位置

opencv 顯示最小面積的外接矩形,並求該矩形的長和寬以及四個角的位置

#include "cv.h"
#include "highgui.h"
#include <stdio.h>
#include <math.h>
int main(int argc,char** argv)
{
 IplImage *src,*gray,*bw,*dst;
    CvMemStorage* storage=cvCreateMemStorage(0);
 CvSeq* contour=0;
 
 char* filename=argc==2?argv[1]:"5.jpg";
  
 if(!filename)
  printf("can't open the file:%d\n",filename);
   
 src=cvLoadImage("D:\\xsz\\Debug\\圖片\\行駛證.jpg",1);

  cvNamedWindow("image",1);
  cvShowImage("image",src);

    gray=cvCreateImage(cvSize(src->width,src->height),src->depth,1);
 cvCvtColor(src,gray,CV_BGR2GRAY);
 int hei,wid;
    hei=gray->height;//注意此處是gray,otsu中要用到hei,wid,已在otsu.h中全域性定義;
 wid=gray->width;
 printf("影象的高為:%d,寬為:%d\n\n",hei,wid);

  cvNamedWindow("image2",1);
     cvShowImage("image2",gray);


    bw=cvCreateImage(cvGetSize(src),IPL_DEPTH_8U,1);
      cvThreshold(gray,bw,128,255,CV_THRESH_BINARY_INV);

 
    cvNamedWindow("image4",1);
  cvShowImage("image4",bw);


  dst=cvCloneImage(src);
  cvFindContours(bw,storage,&contour,sizeof(CvContour),CV_RETR_TREE,CV_CHAIN_APPROX_SIMPLE);
 for(;contour!=0;contour=contour->h_next)

 { CvBox2D rect=cvMinAreaRect2(contour,storage);

  CvPoint2D32f rect_pts0[4];
  cvBoxPoints(rect, rect_pts0);//在c++中已經被廢除。

//因為cvPolyLine要求點集的輸入型別是CvPoint**
//所以要把 CvPoint2D32f 型的 rect_pts0 轉換為 CvPoint 型的 rect_pts
//並賦予一個對應的指標 *pt
int npts = 4,k=0;
int aaa=0,bbb=0;
CvPoint rect_pts[4], *pt = rect_pts;

printf("連通區域最小外接矩形頂點座標分別為:\n");
for (int i=0; i<4; i++)
{
 rect_pts[i]= cvPointFrom32f(rect_pts0[i]);
  printf("%d %d\n",rect_pts[i].x,rect_pts[i].y);
  aaa=(int)sqrt((pow((rect_pts[0].x-rect_pts[1].x),2)+pow((rect_pts[0].y-rect_pts[1].y),2)));
  bbb=(int)sqrt((pow((rect_pts[0].x-rect_pts[3].x),2)+pow((rect_pts[0].y-rect_pts[3].y),2)));

   if(aaa<bbb)
    {
     k=aaa;
     aaa=bbb;
     bbb=k;
    }

}
printf("最小外接矩形的長為:%d,寬為:%d。\n\n",aaa,bbb);
cvPolyLine(dst, &pt, &npts, 1, 1, CV_RGB(255,0,0), 1);
 }
 cvNamedWindow("image5",1);
  cvShowImage("image5",dst);

  cvWaitKey(0);//注意此句放的位置,放的不對則。。。
  
cvDestroyWindow("image");
cvDestroyWindow("image2");
cvDestroyWindow("image4");
cvDestroyWindow("image5");

cvReleaseImage(&src);
cvReleaseImage(&gray);
cvReleaseImage(&bw);
cvReleaseImage(&dst);
  
  return 0;
}