OpenCV最小外接矩形

cvMinAreaRect2(contour,storage)最小外接矩形

#include "stdafx.h"

#include "cv.h"

#include "highgui.h"

#include "cxcore.h"

#include "math.h"

int main(int argc, char* argv[])

{    

 IplImage *src; 

 IplImage *dst;

 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);

 for (int i=0;i120)

        {

            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) 

 { 

CvBox2D rect=cvMinAreaRect2(contour,storage); 

CvPoint2D32f rect_pts0[4]; 

cvBoxPoints(rect, rect_pts0); 

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

 

原图:

OpenCV最小外接矩形_第1张图片

 

二值黑白颠倒图:

OpenCV最小外接矩形_第2张图片

结果图:

OpenCV最小外接矩形_第3张图片

外接矩形信息:

OpenCV最小外接矩形_第4张图片

你可能感兴趣的:(OpenCV)