车道线检测是辅助驾驶和自动驾驶的重要研究内容,相关的算法研究已经延续了20多年,本系列文章旨在帮助初学者在阅读文献之余快速上手构建自己的项目。OpenCV极大地方便了机器视觉应用的编写,为了能在刚起步时就看得远些,我们需要站在OpenCV巨人的肩膀上。
先看一个比较简单的程序,Github地址
框架
class LaneDetect
封装核心算法void makeFromVid(string path)
根据视频文件目录读入,对视频中的图像帧进行处理- 主函数 调用makeFromVid
核心算法
整个算法的核心在blobRemoval函数中:
- findContours函数提取轮廓
- 对找到的轮廓进行筛选:
- contourArea轮廓足够大(高于设定的阈值minSize)
- minAreaRect拟合矩形的有足够长的边(高于设定的阈值longLane )
- 根据矩形的偏角和位置再筛选
- 绘制满足条件的轮廓
这个算法非常简单,效果较差。属于利用车道线的基本几何特征和位置的算法。
完整源程序
/*TODO
* improve edge linking
* remove blobs whose axis direction doesnt point towards vanishing pt
* Parallelisation
* lane prediction
*/
#include <opencv2/core/core.hpp>
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
#include <time.h>
using namespace std;
using namespace cv;
clock_t start, stop;
class LaneDetect
{
public:
Mat currFrame; //stores the upcoming frame
Mat temp; //stores intermediate results
Mat temp2; //stores the final lane segments
int diff, diffL, diffR;
int laneWidth;
int diffThreshTop;
int diffThreshLow;
int ROIrows;
int vertical_left;
int vertical_right;
int vertical_top;
int smallLaneArea;
int longLane;
int vanishingPt;
float maxLaneWidth;
//to store various blob properties
Mat binary_image; //used for blob removal
int minSize;
int ratio;
float contour_area;
float blob_angle_deg;
float bounding_width;
float bounding_length;
Size2f sz;
vector< vector<Point> > contours;
vector<Vec4i> hierarchy;
RotatedRect rotate