日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++?OpenCV實戰之車道檢測_C 語言

作者:Zero___Chen ? 更新時間: 2022-04-03 編程語言

前言

本文將使用OpenCV C++ 進行車道檢測。

一、獲取車道ROI區域

原圖如圖所示。

使用下面代碼段獲取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);

}

mask圖像如圖所示。有了mask圖像,我們就可以更好的進行后續處理,以檢測車道線。

二、車道檢測

1.灰度、閾值

	Mat gray;
	cvtColor(image, gray, COLOR_BGR2GRAY);

	Mat thresh;
	threshold(gray, thresh, 180, 255, THRESH_BINARY);
	imshow("thresh", thresh);

經過灰度、閾值后的圖像如下圖所示。

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));
	}

最終效果如圖所示。

總結

本文使用OpenCV C++進行車道檢測,關鍵步驟有以下幾點。

1、要根據車道所在位置扣出一個ROI區域,這樣方便我們后續的閾值操作。

2、根據閾值圖像獲取左右車道的輪廓點。這里的閾值處理很重要,直接會影響最后的效果。本文做實時視頻處理時,也會因為閾值問題導致最后的效果不是特別好。

3、根據獲取到的各車道輪廓點拿出首尾Point就可以繪制車道線以及車道區域了。

原文鏈接:https://blog.csdn.net/Zero___Chen/article/details/119666454

欄目分類
最近更新