opencv 簡單的檢測直線
阿新 • • 發佈:2018-11-11
//2.4.0 #include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/imgproc/types_c.h> #include <math.h> using namespace cv; using namespace std; void my(Mat &img) { //中值濾波 medianBlur(img,img,3); //邊緣檢測 上下和左右 Mat bmp = img.clone(); Sobel(img,bmp,CV_8U,0,1); Sobel(img,img,CV_8U,1,0); img = img | bmp; //整合到一幅圖 bmp.release(); //二值化 otsu threshold(img, img, 0, 255, CV_THRESH_OTSU); //threshold(img, img, 30, 255, CV_THRESH_BINARY); //adaptiveThreshold(img,img,255,ADAPTIVE_THRESH_MEAN_C,CV_THRESH_BINARY,51,3); //膨脹 腐蝕 閉操作 3x3長方形 Mat e = getStructuringElement(MORPH_RECT,Size(3,3)); dilate(img,img,e); erode(img,img,e); //霍夫變換 vector<Vec4i> lines; HoughLinesP(img, lines, 1, CV_PI/90, 50, 50, 5); //為了畫綠線 單通道轉換為三通道 cvtColor(img, img, CV_GRAY2BGR); //畫出線段 for( size_t i = 0; i < lines.size(); i++ ) { //綠線 line( img, Point(lines[i][0],lines[i][1]), Point(lines[i][2],lines[i][3]), Scalar(0,255,0), 1, CV_AA); } } int main() { Mat im; Mat img=imread("2.bmp",0); im = img.clone(); my(img); //------------------------------------- imshow("我的演算法",img); imshow("原圖",im); waitKey(0); }