欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++ OpenCV实战之车道检测

程序员文章站 2022-06-22 11:55:33
目录前言一、获取车道roi区域二、车道检测1.灰度、阈值2.获取非零像素点3.绘制车道线总结前言本文将使用opencv c++ 进行车道检测。一、获取车道roi区域原图如图所示。使用下面代码段获取ro...

前言

本文将使用opencv c++ 进行车道检测。

一、获取车道roi区域

C++ OpenCV实战之车道检测

原图如图所示。

使用下面代码段获取roi区域。该roi区域点集根据图像特征自己设定。通过fillpoly填充roi区域,最终通过copyto在原图中扣出roi。

void getroi(mat src, mat &image)
{
    mat mask = mat::zeros(src.size(), src.type());

    int width = src.cols;
    int height = src.rows;

    //获取车道roi区域,只对该部分进行处理
    vector<point>pts;
    point pta((width / 8) * 2, (height / 20) * 19);
    point ptb((width / 8) * 2, (height / 8) * 7);
    point ptc((width / 10) * 4, (height / 5) * 3);
    point ptd((width / 10) * 5, (height / 5) * 3);
    point pte((width / 8) * 7, (height / 8) * 7);
    point ptf((width / 8) * 7, (height / 20) * 19);
    pts = { pta ,ptb,ptc,ptd,pte, ptf };

    fillpoly(mask, pts, scalar::all(255));
    src.copyto(image, mask);

}

C++ OpenCV实战之车道检测

mask图像如图所示。有了mask图像,我们就可以更好的进行后续处理,以检测车道线。

二、车道检测

1.灰度、阈值

	mat gray;
	cvtcolor(image, gray, color_bgr2gray);

	mat thresh;
	threshold(gray, thresh, 180, 255, thresh_binary);
	imshow("thresh", thresh);

经过灰度、阈值后的图像如下图所示。

C++ OpenCV实战之车道检测

2.获取非零像素点

我们将图像分为两半。左半边获取左侧车道轮廓点;右半边获取右侧车道轮廓点。

	vector<point>left_line;
	vector<point>right_line;

	for (int i = 0; i < thresh.cols / 2; i++)
	{
		for (int j = 0; j < thresh.rows; j++)
		{
			if (thresh.at<uchar>(j, i) == 255)
			{
				left_line.push_back(point(i, j));

			}
		}
	}

	for (int i = thresh.cols / 2; i < thresh.cols; i++)
	{
		for (int j = 0; j < thresh.rows; j++)
		{
			if (thresh.at<uchar>(j, i) == 255)
			{
				right_line.push_back(point(i, j));
			}
		}
	}

3.绘制车道线

我们将从left_line、right_line容器中各拿出首尾两个点作为车道线的起始点。

注意:这里要加一个if判断语句,否则当容器为空时(未检测到车道线),容器会溢出。

	if (left_line.size() > 0 && right_line.size() > 0)
	{
		point b_l = (left_line[0]);
		point t_l = (left_line[left_line.size() - 1]);
		point t_r = (right_line[0]);
		point b_r = (right_line[right_line.size() - 1]);

		circle(src, b_l, 10, scalar(0, 0, 255), -1);
		circle(src, t_l, 10, scalar(0, 255, 0), -1);
		circle(src, t_r, 10, scalar(255, 0, 0), -1);
		circle(src, b_r, 10, scalar(0, 255, 255), -1);

		line(src, point(b_l), point(t_l), scalar(0, 255, 0), 10);
		line(src, point(t_r), point(b_r), scalar(0, 255, 0), 10);

		vector<point>pts;
		pts = { b_l ,t_l ,t_r ,b_r };
		fillpoly(src, pts, scalar(133, 230, 238));
	}

C++ OpenCV实战之车道检测

最终效果如图所示。

总结

本文使用opencv c++进行车道检测,关键步骤有以下几点。

1、要根据车道所在位置扣出一个roi区域,这样方便我们后续的阈值操作。

2、根据阈值图像获取左右车道的轮廓点。这里的阈值处理很重要,直接会影响最后的效果。本文做实时视频处理时,也会因为阈值问题导致最后的效果不是特别好。

3、根据获取到的各车道轮廓点拿出首尾point就可以绘制车道线以及车道区域了。

到此这篇关于c++ opencv实战之车道检测的文章就介绍到这了,更多相关c++ opencv车道检测内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!