OpenCV入門:Hough霍夫變換-直線選擇(HoughLinesP)
阿新 • • 發佈:2018-12-25
霍夫變換HoughLinesP函式
#include <iostream> #include <fstream> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <math.h> using namespace cv; using namespace std; void drawDetectLines(Mat& image, const vector<Vec4i>& lines, Scalar & color) { // 將檢測到的直線在圖上畫出來 vector<Vec4i>::const_iterator it = lines.begin(); while (it != lines.end()) { Point pt1((*it)[0], (*it)[1]); Point pt2((*it)[2], (*it)[3]); line(image, pt1, pt2, color, 2); // 線條寬度設定為2 ++it; } } int main() { Mat image = imread("E:/CV/11.jpg"); Mat I; cvtColor(image, I, CV_BGR2GRAY); Mat contours; Canny(I, contours, 125, 350); threshold(contours, contours, 128, 255, THRESH_BINARY); vector<Vec4i> lines; /* 霍夫變換HoughLinesP函式的原型為: void HoughLinesP(InputArray image,OutputArray lines, double rho, double theta, int threshold, double minLineLength=0,double maxLineGap=0 ) image為輸入影象,要求是8位單通道影象 lines為輸出的直線向量,每條線用4個元素表示,即直線的兩個端點的4個座標值 rho和theta分別為距離和角度的解析度 threshold為閾值,即步驟3中的閾值 minLineLength為最小直線長度,在步驟5中要用到,即如果小於該值,則不被認為是一條直線 maxLineGap為最大直線間隙,在步驟4中要用到,即如果有兩條線段是在一條直線上,但它們之間因為有間隙,所以被認為是兩個線段,如果這個間隙大於該值,則被認為是兩條線段,否則是一條。 */ // 檢測直線,最小投票為90,線條不短於50,間隙不小於10 HoughLinesP(contours, lines, 1, CV_PI / 180, 80, 50, 10); drawDetectLines(image, lines, Scalar(0, 255, 0)); namedWindow("直線"); imshow("直線", image); waitKey(); return 0; }
效果圖: