opencv 簡單的實現HoughLinesP
阿新 • • 發佈:2018-11-11
//兩點之間的距離 double juli(int x1,int y1,int x2,int y2) { return sqrt(double((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))); } //輸入經過霍夫變換得到的直線 儲存起點和終點的vector 直線最短距離 點之間間隔最長距離 void HoughLinesP(Mat &img,vector<Vec2f> &lines,vector<Vec4i> &points, double minLineLength=0,double maxLineGap=1) { Vec4i point; uchar *p; float r,theta; bool start,end; int x,y; for(size_t i = 0;i < lines.size(); i++) { r = lines[i][0]; theta = lines[i][1]; start = false; end = false; //水平 極徑與x軸90 直線與x軸0 if(sin(theta) > 0.99999) { y = cvRound(r); p = img.ptr<uchar>(y); for(x = 0; x < img.cols; x++) { if( (p[x] != 0) || (x == img.cols - 1) ) { //起點 if(start == false) { point[0] = x; point[1] = y; start = true; continue; } //終點 if(end == false) { //初始一個終點 if(juli(point[0],point[1],x,y) <= maxLineGap) { point[2] = x; point[3] = y; end = true; } //不符合則重新確立起點 else { point[0] = x; point[1] = y; } continue; } //移動終點 if(juli(point[2],point[3],x,y) <= maxLineGap) { point[2] = x; point[3] = y; } else { //確定一條直線 if(juli(point[0],point[1],point[2],point[3]) >= minLineLength) { points.push_back(point); } start = false; end = false; } } } } else { for(y = 0; y < img.rows; y++) { x = cvRound((r-y*sin(theta))/cos(theta)); p = img.ptr<uchar>(y); if( (p[x] != 0) || (y == img.rows - 1) ) { //起點 if(start == false) { point[0] = x; point[1] = y; start = true; continue; } //終點 if(end == false) { //初始一個終點 if(juli(point[0],point[1],x,y) <= maxLineGap) { point[2] = x; point[3] = y; end = true; } //不符合則重新確立起點 else { point[0] = x; point[1] = y; } continue; } //移動終點 if(juli(point[2],point[3],x,y) <= maxLineGap) { point[2] = x; point[3] = y; } else { //確定一條直線 if(juli(point[0],point[1],point[2],point[3]) >= minLineLength) { points.push_back(point); } start = false; end = false; } } } } } }