C++ opencv实现车道线识别
程序员文章站
2022-05-22 14:27:38
本文实例为大家分享了c++ opencv实现车道线识别的具体代码,供大家参考,具体内容如下先上图1、2、(一)目前国内外广泛使用的车道线检测方法主要分为两大类:(1) 基于道路特征的车道线检测;(2)...
本文实例为大家分享了c++ opencv实现车道线识别的具体代码,供大家参考,具体内容如下
先上图
1、
2、
(一)目前国内外广泛使用的车道线检测方法主要分为两大类:
(1) 基于道路特征的车道线检测;
(2) 基于道路模型的车道线检测。
基于道路特征的车道线检测作为主流检测方法之一,主要是利用车道线与道路环境的物理特征差异进行后续图像的分割与处理,从而突出车道线特征,以实现车道线的检测。该方法复杂度较低,实时性较高,但容易受到道路环境干扰。
基于道路模型的车道线检测主要是基于不同的二维或三维道路图像模型(如直线型、抛物线型、样条曲线型、组合模型等) ,采用相应方法确定各模型参数,然后进行车道线拟合。该方法对特定道路的检测具有较高的准确度,但局限性强、运算量大、实时性较差。
(二)在这我介绍一种车道线检测方法,效果在高速上还可以,对于破损道路,光照变化太大等道路效果不佳,后续继续改进(直方图均衡以及多特征融合等等),这里有个基础版本的接口,大致步骤如下
(1)图像灰度化
(2)图像高斯滤波
(3)边缘检测
(4)获取掩膜,获取感兴趣区域
(5)霍夫变换检测直线
(6)将检测到的车道线分类,设置阈值,以图像中线分为左右两边的车道线,存入一个vector
(7)回归两条直线,即左右分别两个点,且求出斜率方程
(8)确定车道线的转弯与否
下面我贴出代码
(1)头文件(lanedetector.h)
class lanedetector { private: double img_size; double img_center; bool left_flag = false; // tells us if there's left boundary of lane detected bool right_flag = false; // tells us if there's right boundary of lane detected cv::point right_b; // members of both line equations of the lane boundaries: double right_m; // y = m*x + b cv::point left_b; // double left_m; // public: cv::mat denoise(cv::mat inputimage); // apply gaussian blurring to the input image cv::mat edgedetector(cv::mat img_noise); // filter the image to obtain only edges cv::mat mask(cv::mat img_edges); // mask the edges image to only care about roi std::vector<cv::vec4i> houghlines(cv::mat img_mask); // detect hough lines in masked edges image std::vector<std::vector<cv::vec4i> > lineseparation(std::vector<cv::vec4i> lines, cv::mat img_edges); // sprt detected lines by their slope into right and left lines std::vector<cv::point> regression(std::vector<std::vector<cv::vec4i> > left_right_lines, cv::mat inputimage); // get only one line for each side of the lane std::string predictturn(); // determine if the lane is turning or not by calculating the position of the vanishing point int plotlane(cv::mat inputimage, std::vector<cv::point> lane, std::string turn); // plot the resultant lane and turn prediction in the frame. };
源文件lanedetector.cpp
*@file lanedetector.cpp *@author miguel maestre trueba *@brief definition of all the function that form part of the lanedetector class. *@brief the class will take rgb images as inputs and will output the same rgb image but *@brief with the plot of the detected lanes and the turn prediction. */ #include <string> #include <vector> #include <opencv2/opencv.hpp> #include "lanedetector.h" // image blurring /** *@brief apply gaussian filter to the input image to denoise it *@param inputimage is the frame of a video in which the *@param lane is going to be detected *@return blurred and denoised image */ cv::mat lanedetector::denoise(cv::mat inputimage) { cv::mat output; cv::gaussianblur(inputimage, output, cv::size(3, 3), 0, 0); return output; } // edge detection /** *@brief detect all the edges in the blurred frame by filtering the image *@param img_noise is the previously blurred frame *@return binary image with only the edges represented in white */ cv::mat lanedetector::edgedetector(cv::mat img_noise) { cv::mat output; cv::mat kernel; cv::point anchor; // convert image from rgb to gray cv::cvtcolor(img_noise, output, cv::color_rgb2gray); // binarize gray image cv::threshold(output, output, 140, 255, cv::thresh_binary); // create the kernel [-1 0 1] // this kernel is based on the one found in the // lane departure warning system by mathworks anchor = cv::point(-1, -1); kernel = cv::mat(1, 3, cv_32f); kernel.at<float>(0, 0) = -1; kernel.at<float>(0, 1) = 0; kernel.at<float>(0, 2) = 1; // filter the binary image to obtain the edges cv::filter2d(output, output, -1, kernel, anchor, 0, cv::border_default); cv::imshow("output", output); return output; } // mask the edge image /** *@brief mask the image so that only the edges that form part of the lane are detected *@param img_edges is the edges image from the previous function *@return binary image with only the desired edges being represented */ cv::mat lanedetector::mask(cv::mat img_edges) { cv::mat output; cv::mat mask = cv::mat::zeros(img_edges.size(), img_edges.type()); cv::point pts[4] = { cv::point(210, 720), cv::point(550, 450), cv::point(717, 450), cv::point(1280, 720) }; // create a binary polygon mask cv::fillconvexpoly(mask, pts, 4, cv::scalar(255, 0, 0)); // multiply the edges image and the mask to get the output cv::bitwise_and(img_edges, mask, output); return output; } // hough lines /** *@brief obtain all the line segments in the masked images which are going to be part of the lane boundaries *@param img_mask is the masked binary image from the previous function *@return vector that contains all the detected lines in the image */ std::vector<cv::vec4i> lanedetector::houghlines(cv::mat img_mask) { std::vector<cv::vec4i> line; // rho and theta are selected by trial and error houghlinesp(img_mask, line, 1, cv_pi / 180, 20, 20, 30); return line; } // sort right and left lines /** *@brief sort all the detected hough lines by slope. *@brief the lines are classified into right or left depending *@brief on the sign of their slope and their approximate location *@param lines is the vector that contains all the detected lines *@param img_edges is used for determining the image center *@return the output is a vector(2) that contains all the classified lines */ std::vector<std::vector<cv::vec4i> > lanedetector::lineseparation(std::vector<cv::vec4i> lines, cv::mat img_edges) { std::vector<std::vector<cv::vec4i> > output(2); size_t j = 0; cv::point ini; cv::point fini; double slope_thresh = 0.3; std::vector<double> slopes; std::vector<cv::vec4i> selected_lines; std::vector<cv::vec4i> right_lines, left_lines; // calculate the slope of all the detected lines for (auto i : lines) { ini = cv::point(i[0], i[1]); fini = cv::point(i[2], i[3]); // basic algebra: slope = (y1 - y0)/(x1 - x0) double slope = (static_cast<double>(fini.y) - static_cast<double>(ini.y)) / (static_cast<double>(fini.x) - static_cast<double>(ini.x) + 0.00001); // if the slope is too horizontal, discard the line // if not, save them and their respective slope if (std::abs(slope) > slope_thresh) { slopes.push_back(slope); selected_lines.push_back(i); } } // split the lines into right and left lines img_center = static_cast<double>((img_edges.cols / 2)); while (j < selected_lines.size()) { ini = cv::point(selected_lines[j][0], selected_lines[j][1]); fini = cv::point(selected_lines[j][2], selected_lines[j][3]); // condition to classify line as left side or right side if (slopes[j] > 0 && fini.x > img_center && ini.x > img_center) { right_lines.push_back(selected_lines[j]); right_flag = true; } else if (slopes[j] < 0 && fini.x < img_center && ini.x < img_center) { left_lines.push_back(selected_lines[j]); left_flag = true; } j++; } output[0] = right_lines; output[1] = left_lines; return output; } // regression for left and right lines /** *@brief regression takes all the classified line segments initial and final points and fits a new lines out of them using the method of least squares. *@brief this is done for both sides, left and right. *@param left_right_lines is the output of the lineseparation function *@param inputimage is used to select where do the lines will end *@return output contains the initial and final points of both lane boundary lines */ std::vector<cv::point> lanedetector::regression(std::vector<std::vector<cv::vec4i> > left_right_lines, cv::mat inputimage) { std::vector<cv::point> output(4); cv::point ini; cv::point fini; cv::point ini2; cv::point fini2; cv::vec4d right_line; cv::vec4d left_line; std::vector<cv::point> right_pts; std::vector<cv::point> left_pts; // if right lines are being detected, fit a line using all the init and final points of the lines if (right_flag == true) { for (auto i : left_right_lines[0]) { ini = cv::point(i[0], i[1]); fini = cv::point(i[2], i[3]); right_pts.push_back(ini); right_pts.push_back(fini); } if (right_pts.size() > 0) { // the right line is formed here cv::fitline(right_pts, right_line, cv_dist_l2, 0, 0.01, 0.01); right_m = right_line[1] / right_line[0]; right_b = cv::point(right_line[2], right_line[3]); } } // if left lines are being detected, fit a line using all the init and final points of the lines if (left_flag == true) { for (auto j : left_right_lines[1]) { ini2 = cv::point(j[0], j[1]); fini2 = cv::point(j[2], j[3]); left_pts.push_back(ini2); left_pts.push_back(fini2); } if (left_pts.size() > 0) { // the left line is formed here cv::fitline(left_pts, left_line, cv_dist_l2, 0, 0.01, 0.01); left_m = left_line[1] / left_line[0]; left_b = cv::point(left_line[2], left_line[3]); } } // one the slope and offset points have been obtained, apply the line equation to obtain the line points int ini_y = inputimage.rows; int fin_y = 470; double right_ini_x = ((ini_y - right_b.y) / right_m) + right_b.x; double right_fin_x = ((fin_y - right_b.y) / right_m) + right_b.x; double left_ini_x = ((ini_y - left_b.y) / left_m) + left_b.x; double left_fin_x = ((fin_y - left_b.y) / left_m) + left_b.x; output[0] = cv::point(right_ini_x, ini_y); output[1] = cv::point(right_fin_x, fin_y); output[2] = cv::point(left_ini_x, ini_y); output[3] = cv::point(left_fin_x, fin_y); return output; } // turn prediction /** *@brief predict if the lane is turning left, right or if it is going straight *@brief it is done by seeing where the vanishing point is with respect to the center of the image *@return string that says if there is left or right turn or if the road is straight */ std::string lanedetector::predictturn() { std::string output; double vanish_x; double thr_vp = 10; // the vanishing point is the point where both lane boundary lines intersect vanish_x = static_cast<double>(((right_m*right_b.x) - (left_m*left_b.x) - right_b.y + left_b.y) / (right_m - left_m)); // the vanishing points location determines where is the road turning if (vanish_x < (img_center - thr_vp)) output = "left turn"; else if (vanish_x >(img_center + thr_vp)) output = "right turn"; else if (vanish_x >= (img_center - thr_vp) && vanish_x <= (img_center + thr_vp)) output = "straight"; return output; } // plot results /** *@brief this function plots both sides of the lane, the turn prediction message and a transparent polygon that covers the area inside the lane boundaries *@param inputimage is the original captured frame *@param lane is the vector containing the information of both lines *@param turn is the output string containing the turn information *@return the function returns a 0 */ int lanedetector::plotlane(cv::mat inputimage, std::vector<cv::point> lane, std::string turn) { std::vector<cv::point> poly_points; cv::mat output; // create the transparent polygon for a better visualization of the lane inputimage.copyto(output); poly_points.push_back(lane[2]); poly_points.push_back(lane[0]); poly_points.push_back(lane[1]); poly_points.push_back(lane[3]); cv::fillconvexpoly(output, poly_points, cv::scalar(0, 0, 255), cv_aa, 0); cv::addweighted(output, 0.3, inputimage, 1.0 - 0.3, 0, inputimage); // plot both lines of the lane boundary cv::line(inputimage, lane[0], lane[1], cv::scalar(0, 255, 255), 5, cv_aa); cv::line(inputimage, lane[2], lane[3], cv::scalar(0, 255, 255), 5, cv_aa); // plot the turn message cv::puttext(inputimage, turn, cv::point(50, 90), cv::font_hershey_complex_small, 3, cvscalar(0, 255, 0), 1, cv_aa); // show the final output image cv::namedwindow("lane", cv_window_autosize); cv::imshow("lane", inputimage); return 0; }
main函数
#include <iostream> #include <string> #include <vector> #include <opencv2/opencv.hpp> #include "lanedetector.h" //#include "lanedetector.cpp" /** *@brief function main that runs the main algorithm of the lane detection. *@brief it will read a video of a car in the highway and it will output the *@brief same video but with the plotted detected lane *@param argv[] is a string to the full path of the demo video *@return flag_plot tells if the demo has sucessfully finished */ int main() { // the input argument is the location of the video cv::videocapture cap("challenge_video.mp4"); if (!cap.isopened()) return -1; lanedetector lanedetector; // create the class object cv::mat frame; cv::mat img_denoise; cv::mat img_edges; cv::mat img_mask; cv::mat img_lines; std::vector<cv::vec4i> lines; std::vector<std::vector<cv::vec4i> > left_right_lines; std::vector<cv::point> lane; std::string turn; int flag_plot = -1; int i = 0; // main algorithm starts. iterate through every frame of the video while (i < 540) { // capture frame if (!cap.read(frame)) break; // denoise the image using a gaussian filter img_denoise = lanedetector.denoise(frame); // detect edges in the image img_edges = lanedetector.edgedetector(img_denoise); // mask the image so that we only get the roi img_mask = lanedetector.mask(img_edges); // obtain hough lines in the cropped image lines = lanedetector.houghlines(img_mask); if (!lines.empty()) { // separate lines into left and right lines left_right_lines = lanedetector.lineseparation(lines, img_edges); // apply regression to obtain only one line for each side of the lane lane = lanedetector.regression(left_right_lines, frame); // predict the turn by determining the vanishing point of the the lines turn = lanedetector.predictturn(); // plot lane detection flag_plot = lanedetector.plotlane(frame, lane, turn); i += 1; cv::waitkey(25); } else { flag_plot = -1; } } return flag_plot; }
最后再晒一张结果图吧
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。