opencv practice project - simple lane line detection

Table of contents

1. Steps

  • Original picture plus mask
  • Convert to grayscale
  • binary detection
  • Gaussian blur
  • edge detection
  • Hough line detection

2. Realize

Original image:
'insert image description here

code:

#include <opencv2/opencv.hpp>
#include <vector>

using namespace cv;
using namespace std;


cv::Mat mask_of_image(cv::Mat image)
{
    
    
    int height = image.rows;//1470, 1106
    cv::Mat mask(image.size(), 0);

    std::vector<cv::Point> polygons{
    
    {
    
    0, height}, {
    
    2200, height}, {
    
    250, 100}};

    cv::fillPoly(mask, vector<std::vector<cv::Point>>{
    
    polygons}, (255,255,255));


    cv::Mat mask_image;

    cv::bitwise_and(image, image, mask_image, mask);

    return mask_image;

}

int main() {
    
    
    //读取图片
    Mat img = imread("/Users/xialz/Downloads/2.png");
    
    //添加蒙版
    cv::Mat gray_img;
    gray_img = mask_of_image(img);
    //转灰度图
    cvtColor(gray_img , gray_img , COLOR_BGR2GRAY);
    //二值化
    cv::Mat threshold_img;
    cv::threshold(gray_img, threshold_img, 200, 255, cv::THRESH_BINARY);
    //高斯模糊
    cv::Mat gauss_img;
    cv::GaussianBlur(threshold_img, gauss_img, Size(5,5), 3);
    //边缘检测
    cv::Mat canny_img;
    cv::Canny(gauss_img, canny_img, 180, 255);

    cv::imshow("canny_img", canny_img);
    //霍夫直线检测
    std::vector<cv::Vec4i> lines;
    cv::HoughLinesP(canny_img, lines, 1., CV_PI / 180, 30);
    
    //画线
    for (int i = 0; i < lines.size(); ++i) {
    
    
        cv::Vec4i line_ = lines[i];
        cv::line(img, cv::Point(line_[0], line_[1]), cv::Point(line_[2], line_[3]), cv::Scalar(0, 255, 0), 2, LINE_AA);
    }

    cv::imshow("img", img);

    waitKey(0);

    return 0;
}

Result graph:
insert image description here

=A few notes=

  • Why add a mask?
    Because without a mask, the cloud above will be recognized, as shown in the figure below:
    insert image description here
  • About the Hough detection function,
    you can refer to the link: link

Guess you like

Origin blog.csdn.net/wyw0000/article/details/130027967