利用Hough变换,求最长的直线。并且得到最长直线 与水平的夹角

/**//* This is a standalone program. Pass an image name as a first parameter
 of the program.Switch between standard and probabilistic Hough transform
by changing "#if 1" to "#if 0" and back */
#include <cv.h>
#include <highgui.h>
#include <math.h>
#include <STDIO.H>
#include <stdio.h>
#include <iostream.h>
int main(int argc, char** argv)
{
    IplImage* src;
    src=cvLoadImage("7.bmp",0);
 
 IplImage* dst = cvCreateImage( cvGetSize(src), 8, 1 );
 IplImage* color_dst = cvCreateImage( cvGetSize(src), 8, 3 );
 CvMemStorage* storage = cvCreateMemStorage(0);
 CvSeq* lines = 0;
 int i;
    IplImage* src1=cvCreateImage(cvSize(src->width,src->height),IPL_DEPTH_8U,1);
 
 //  cvCvtColor(src, src1, CV_BGR2GRAY); 
    cvCopy(src,src1);
 cvCanny( src1, dst, 50, 200, 3 );
 
 cvCvtColor( dst, color_dst, CV_GRAY2BGR );
 
 cvNamedWindow("src",1);
 cvShowImage("src",dst);
 
 lines = cvHoughLines2( dst, storage, CV_HOUGH_PROBABILISTIC, 1, CV_PI/180, 10, 30, 10 );
 printf("%d\n",lines->total);
 int dis=0;
 int max=0;
 int j=0;
 CvPoint* line;
 CvPoint pointOne;
 CvPoint pointTwo;
 int a[1003]={0};
 for( i = 0; i < lines->total; i++ )
 {
  line = (CvPoint*)cvGetSeqElem(lines,i);
  
  dis=(line[1].y-line[0].y)*(line[1].y-line[0].y)+(line[1].x-line[0].x)*(line[1].x-line[0].x);
  
  //  pointOne[i].x=line[0].x;
  //   pointOne[i].y=line[0].y;
  //    pointTwo[i].x=line[1].x;
  //pointTwo[i].y=line[1].y;
  a[4*i]=line[0].x;
  a[4*i+1]=line[0].y;
  a[4*i+2]=line[1].x;
  a[4*i+3]=line[1].y;
  if(dis>max)
  {
   max=dis;
   j=i;
  }
  // cvLine( color_dst, line[0], line[1], CV_RGB(255,0,0), 3, 8 );
 }
 pointOne.x=a[4*j];
 pointOne.y=a[4*j+1];
 pointTwo.x=a[4*j+2];
 pointTwo.y=a[4*j+3];
 cvLine( color_dst, pointOne, pointTwo, CV_RGB(255,0,0), 3, 8 );    //画出最长的直线
 
 
 double Angle=0.0;
 
 Angle = atan2(fabs(pointTwo.y-pointOne.y),fabs(pointTwo.x-pointOne.x));   //得到最长直线与水平夹角
 
 if(pointTwo.x>pointOne.x && pointTwo.y>pointOne.y)
 {
  Angle=-Angle;
 }
 
 Angle=Angle*180/CV_PI;
 cout<<"角度 "<<Angle<<endl;
 cvNamedWindow( "Source", 1 );
 cvShowImage( "Source", src );
 
 cvNamedWindow( "Hough", 1 );
 cvShowImage( "Hough", color_dst );
 
 cvWaitKey(0);
   
}


 

posted on 2008-11-09 15:16  wqj1212  阅读(2930)  评论(1编辑  收藏  举报

导航