3. 直线检测

示例代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
 检测填空题中的直线: 采用形态学方式
*/
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

Mat src,result;
int threshold_value=95;
int max_count=255;

void detectline(int,void*);

int main(){
    string path = "/home/kaijun/Documents/resource/opencv/engline.jpg";

    src = imread(path,IMREAD_COLOR);
    imshow("src0",src);
    detectline();
    createTrackbar("threshold1","src",&threshold_value,max_count,detectline);

    waitKey(0);
    return 0;
}

void detectline(int ,void*){

    // 将彩色图转成灰度图
    Mat gray;
    cvtColor(src,gray,COLOR_BGR2GRAY);

    // 1. 将图像进行二值化处理
    Mat binary;
    threshold(gray,binary,0,255,THRESH_BINARY_INV|THRESH_OTSU);
    imshow("binary",binary);

    // 2. 形态学操作
    Mat morph;
    Mat kernel = getStructuringElement(MORPH_RECT, Size(20, 1));
    morphologyEx(binary,morph,MORPH_OPEN,kernel);
    imshow("morphology",morph);

    // 3. 膨胀一下
    Mat kernel2 = getStructuringElement(MORPH_RECT,Size(3,3));
    dilate(morph,morph,kernel2);
    imshow("morphology2",morph);

    // 4. 寻找霍夫直线
    vector<Vec4i> lines;
    HoughLinesP(morph,lines,1,CV_PI/180,30,20,0);

    for(int i=0; i < lines.size();i++){
        Vec4i ln = lines[i];
        line(src,Point(ln[0],ln[1]),Point(ln[2],ln[3]),Scalar(0,0,255),1);
    }

    imshow("src",src);
}