车道线检测草稿

#include <iostream>    // for standard I/O
#include <cmath> 
#include <cstdlib> 
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;

Mat yellowLine(Mat src, int avg);

int main(int argc, char *argv[])
{
	Mat src, ROI, gray, thresh, src_clone, ROI_clone;
	double ROI_row_rate = 3;
	int L = 200;
	VideoCapture camera("2.mp4");
	while (camera.isOpened()) {
		camera >> src;
		//原图长宽
		int height = src.rows;
		int width = src.cols;
		src_clone = src.clone();
		//感兴趣区域的左上角坐标与右下角坐标
		Point point_left_up = Point(L, height - height / ROI_row_rate);
		Point point_right_down = Point(width - L, height - 10);
		
		//提取感兴趣区域
		Rect rect = Rect(point_left_up, point_right_down);
		ROI = Mat(src, rect);
		ROI_clone = ROI.clone();
		//roi长宽
		int ROI_height = ROI.rows;
		int ROI_width = ROI.cols;
		//在原图中画出感兴趣区域
		rectangle(src_clone, point_left_up, point_right_down, Scalar(0, 255, 0), 2, 8, 0);
		
		
		cvtColor(ROI, gray, COLOR_BGR2GRAY);
		//画出中线
		line(src_clone, Point(src.cols / 2, height - height / ROI_row_rate), Point(width / 2, height - 10), Scalar(0, 0, 255), 2, 8, 0);
		
		//计算整体平均亮度
		int sum = 0, avg;
		for (int i = 0; i < ROI_height; i++) {
			uchar *p = gray.ptr(i);
			for (int j = 0; j < ROI_width; j++) {
				sum += (int)p[j];
			}
		}

		avg = sum / (ROI_height * ROI_width);
		cout << avg << endl;
	//	Mat test = yellowLine(ROI_clone, avg);
		//根据平均亮度确定阈值
		threshold(gray, thresh, saturate_cast<uchar>(avg + 50), 255, THRESH_BINARY);

		Canny(thresh, thresh, 20, 80, 3, false);
		vector<vector<Point>> contours;
		vector<Vec4i> hierarchy;
		findContours(thresh, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));

		for (int i = 0; i < contours.size(); i++)
		{
			Scalar color = Scalar(255, 0, 0);
			drawContours(thresh, contours, i, color, 1, 8, hierarchy, 0, Point(0, 0));
		}



		int minLineLength = 20;
		int maxLineGap = 5;
		vector<Vec4f> lines;
		//'1'生成极坐标时候的像素扫描步长,'CV_PI/180'生成极坐标时候的角度步长,'10'最小直线长度,'0'最大间隔(能构成一条直线) 
		HoughLinesP(thresh, lines, 1, CV_PI / 180, 50, 20, 50);
		
		for (size_t i = 0; i < lines.size(); i++)
		{
			Vec4f plines = lines[i];  //一个plines里边是四个点一条直线 
			plines[0] += L;
			plines[1] += (height - height / ROI_row_rate);
			plines[2] += L;
			plines[3] += (height - height / ROI_row_rate);
			//剔除横线
			if(abs(plines[1] - plines[3]) > 50)
			line(src_clone, Point(plines[0], plines[1]), Point(plines[2], plines[3]), Scalar(255, 255, 0.8), 5, 8, 0);

		}
		imshow("ROI",thresh);
		imshow("src", src_clone);
		//imshow("test", test);
		waitKey(27);
	}
	
}


Mat yellowLine(Mat src, int avg) {
	Mat gray, thresh;
	cvtColor(src, gray, COLOR_BGR2GRAY);
	threshold(gray, thresh, avg + avg / 2.4, 255, THRESH_BINARY);
	return thresh;
}

猜你喜欢

转载自blog.csdn.net/qq_40238526/article/details/90301875