基于霍夫变换条件筛选的车道线识别-Opencv实现

来源:互联网 发布:淘宝贷款100万还不上 编辑:程序博客网 时间:2024/05/17 23:07

程序是基于MFC的,所以只有部分,必须修改下才能运行;

这是做车道识别最原始的想法

效果很一般的,不实际,霍夫变换相当耗时ddd

float keytheta=0.0,keyrho=0.0;vector<Vec2f> GetThreeLineEx(Mat line,int colhaf){/*if (line.cols<=3){return line;}*/vector<Vec2f> threeline;int idx=0;float distance=0.0;Vec2f tempVec;Vec2f VEC;VEC[0]=0;VEC[1]=CV_PI/2;float theta2;float rho;float theta;double sum;for(int i=1;i<=5;i++){sum=CV_PI;tempVec[0]=0;tempVec[1]=0;for (int k=0;k<line.cols;k++){rho=line.at<Vec2f>(k)[0];theta=line.at<Vec2f>(k)[1];if (theta>(CV_PI/3.0)&&theta<(CV_PI*2/3.0)){continue;}if (theta<(CV_PI/36.0)||((CV_PI-theta)<CV_PI/36.0)){if (abs(rho-colhaf)>20){continue;}}distance=abs(rho-keyrho*cos(theta-keytheta));if (distance>50){continue;}if (theta>CV_PI/2.0){theta2=CV_PI-theta;}else{theta2=theta;}if (theta2<sum){sum=theta2;tempVec[0]=rho;tempVec[1]=theta;idx=k;}}if (tempVec[0]!=0){line.at<Vec2f>(idx)=VEC;threeline.push_back(tempVec);}}return threeline;}void COpenCV_testDlg::VideoTest(Mat frame){Mat frame_gray;cvtColor( frame, frame_gray, CV_BGR2GRAY );//do hereMat img;Mat temp;//resize(frame_gray,frame_gray,Size(0,0),0.5,0.5,INTER_LINEAR);blur(frame_gray,frame_gray,Size(3,3));Canny(frame_gray, frame_gray, 30, 90, 3);keytheta=atan(2.0*frame.rows/frame.cols/3.0);keyrho=0;keyrho=sqrt(pow(frame.cols/2.0,2)+pow(frame.rows/3.0,2));Mat hl;vector<Vec2f> lines;HoughLines(frame_gray, hl, 1, CV_PI/180, 100, 0, 0 );imshow( "gray", frame_gray );lines=GetThreeLineEx(hl,frame_gray.cols/2);for( size_t i = 0; i < lines.size(); i++ ){float rho = lines[i][0], theta = lines[i][1];Point pt1, pt2;double a = cos(theta), b = sin(theta);double x0 = a*rho, y0 = b*rho;pt1.x = cvRound(x0 + 1000*(-b));pt1.y = cvRound(y0 + 1000*(a));pt2.x = cvRound(x0 - 1000*(-b));pt2.y = cvRound(y0 - 1000*(a));line( frame, pt1, pt2, Scalar(0,0,255), 2, CV_AA);}//imshow( "edges", frame );}void COpenCV_testDlg::PlayVideoFromAVI(CString filepath){UpdateData(TRUE);USES_CONVERSION;//调用函数,T2A和W2A均支持ATL和MFC中的字符转换char * pFileName = T2A(filepath);m_cap.open(pFileName); // open the default cameraif(!m_cap.isOpened()) // check if we succeeded{AfxMessageBox(_T("open avi file error"));return;}int iFramCount=(int)m_cap.get(CV_CAP_PROP_FRAME_COUNT);if (iFramCount!=0){m_SliderCtrl.SetRange(0,iFramCount-1,TRUE);m_SliderCtrl.SetPos(0);}//Mat edges;//namedWindow(window_name,1);namedWindow("edges",1);//Mat frame;while(1){//cap >> frame; // get a new frame from cameraif (m_PauseFlage){}else{if (m_cap.read(frame)){VideoTest(frame);m_SliderCtrl.SetPos((int)m_cap.get(CV_CAP_PROP_POS_FRAMES));}else{return;}}if(waitKey(30) >= 0)break;}//frame.release();//edges.release();}