opencv檢測圖像直線

  

 1 #include<opencv2/opencv.hpp>
 2 #include<iostream>
 3 using namespace std;  4 using namespace cv;  5 Mat src, dst;  6 int main(void) {  7     src = imread("..\\lineDetect.jpg");  8     if (src.empty()) {  9         cout << "Loading image failed!" << endl; 10         return -1; 11  } 12 
13     //圖片大小不合適,先對圖片進行縮放
14     resize(src, src, Size(src.rows/5, src.cols/5)); 15     imshow("Sources image", src); 16     //圖片的方向不對,用仿射變換調整至正確位置 17     //圖片須要逆時針旋轉90度
18     double angel = 90; 19     Point center = Point(src.cols/2,src.rows/2); 20     //因爲仿射變換後致使圖像不全,用下面方法解決
21     Rect mask = RotatedRect(center, Size(src.cols,src.rows), angel).boundingRect(); 22     //對仿射中心進行調整
23     Mat h = getRotationMatrix2D(center, angel, 1); 24     h.at<double>(0, 2) += mask.width / 2 - center.x; 25     h.at<double>(1, 2) += mask.height / 2 - center.y; 26     //獲取仿射矩陣
27  Mat temp; 28     warpAffine(src, temp, h ,Size(src.rows,src.cols),1,0,Scalar(255,255,255)); 29  copyTo(temp, dst, Mat()); 30 
31  Mat gray; 32  cvtColor(temp, gray, COLOR_BGR2GRAY); 33     //反向二值化圖像
34  Mat binary; 35     threshold(gray, binary, 160,255, THRESH_BINARY_INV); 36     //經過開操做消除文字,保留直線
37     Mat kernel = getStructuringElement(MORPH_RECT, Size(20, 2)); 38  morphologyEx(binary, binary, MORPH_OPEN, kernel); 39     //經過膨脹操做使直線更明顯
40     Mat kernel1 = getStructuringElement(MORPH_RECT, Size(3, 3)); 41  dilate(binary, binary, kernel1); 42     //imshow("temp image",binary); 43     //霍夫直線檢測
44     vector<Vec4f> linesPoint; 45     HoughLinesP(binary, linesPoint, 1, CV_PI / 180, 20, 0, 0); 46     for (int i = 0; i < linesPoint.size(); i++){ 47         line(dst, Point(linesPoint[i][0], linesPoint[i][1]), Point(linesPoint[i][2], linesPoint[i][3]), Scalar(0,255,0), 2); 48  } 49     imshow("Object image", dst); 50     waitKey(0); 51     return 0; 52 }

    結果:ios

   代碼中關於仿射變換,有不懂的能夠去看看這篇博客:https://blog.csdn.net/u013105205/article/details/78826789spa

相關文章
相關標籤/搜索