opencv实践::直线检测

 

问题描述
  寻找英语试卷填空题的下划线,这个对后期的切图与自动 识别都比较重要。

 

 解决思路 
  方法: 通过图像形态学操作来寻找直线,霍夫获取位置信息与显示。

 

 

 

#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>

using namespace cv;
using namespace std;

#define IMAGE_PATH "D:/case3.png"
int max_count = 255;
int threshold_value = 100;
const char* output_lines = "Hough Lines";


Mat src, roiImage, dst;
void morhpologyLines(int, void*);
int main(int argc, char** argv) {
    src = imread(IMAGE_PATH, IMREAD_GRAYSCALE);
    if (src.empty()) {
        printf("could not load image...\n");
        return -1;
    }
    namedWindow("input image", CV_WINDOW_AUTOSIZE);
    imshow("input image", src);
    namedWindow(output_lines, CV_WINDOW_AUTOSIZE);
    Rect roi = Rect(10, 10, src.cols - 20, src.rows - 20);
    roiImage = src(roi);
    //imshow("ROI image", roiImage);

    morhpologyLines(0, 0);

    waitKey(0);
    return 0;
}


void morhpologyLines(int, void*) {
    // 二值化
    Mat binaryImage, morhpImage;
    // 图像的二值化,就是将图像上的像素点的灰度值设置为0或255,也就是将整个图像呈现出明显的只有黑和白的视觉效果。
    threshold(roiImage, binaryImage, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
    //imshow("binary", binaryImage);

    // 定义一个结构元素 宽40像素,高1像素
    Mat kernel = getStructuringElement(MORPH_RECT, Size(40, 1), Point(-1, -1));
    morphologyEx(binaryImage, morhpImage, MORPH_OPEN, kernel, Point(-1, -1));
    //imshow("morphology result", morhpImage);

    // 膨胀强化直线
    kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
    dilate(morhpImage, morhpImage, kernel);
    //imshow("morphology lines", morhpImage);

    // 霍夫直线标定
    vector<Vec4i> lines;
    HoughLinesP(morhpImage, lines, 1, CV_PI / 180.0, 30, 20.0, 0);
    Mat resultImage = roiImage.clone();
    cvtColor(resultImage, resultImage, COLOR_GRAY2BGR);
    for (size_t t = 0; t < lines.size(); t++) {
        Vec4i ln = lines[t];
        line(resultImage, Point(ln[0], ln[1]), Point(ln[2], ln[3]), Scalar(0, 0, 255), 2, 8, 0);
    }
    imshow(output_lines, resultImage);
    return;
}

 

posted @ 2019-10-12 14:25  osbreak  阅读(882)  评论(0编辑  收藏  举报