zoukankan      html  css  js  c++  java
  • 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 }

        结果:

       代码中关于仿射变换,有不懂的可以去看看这篇博客:https://blog.csdn.net/u013105205/article/details/78826789

  • 相关阅读:
    2050大会,让世界离年青人更近,让年青人离世界更近
    2050大会,让世界离年青人更近,让年青人离世界更近
    Mybatis-Configuration-详解
    Mybatis-Configuration-详解
    .NET内置的Ajax工作原理
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
  • 原文地址:https://www.cnblogs.com/yuxi-blog/p/10848467.html
Copyright © 2011-2022 走看看