Matlab 车道识别(简单例子)

需将Lane2.jpg照片放在工作目录

 

% 车道线检测  只能检测 实线+直线,

clc;
clear;

srcImage=imread('Lane2.jpg');%读取图形 


grayImage=rgb2gray(srcImage);%灰度化


denoisedImage=medfilt2(grayImage,[9,9]);%中值滤波
%边缘增强
H=fspecial('sobel'); %sobel算子
sobelImage=imfilter(denoisedImage,H);
%图像二值化
thresh=graythresh(sobelImage);%通过Otsu方法获得阈值
binaryImage=imbinarize(sobelImage,thresh);


%hough变换
[H, theta,rho]=hough(binaryImage);
p=houghpeaks(H,5,'threshold',ceil(0.3*max(H(:)))); %获取hough空间中前5个最大值点
lines=houghlines(binaryImage,theta,rho,p,'FillGap',20,'MinLength',40);%将hough空间中最大值转换为图像中的直线段

%%%%%%%%%%%%%%%%%%%%%%%%%  结果筛选及可视化  %%%%%%%%%%%%%%%%%%%%%%%%% 
subplot(2,2,1),  imshow(srcImage),title('1-原图');  % imshow(srcImage);  %%%%显示中间状态  原图
subplot(2,2,2),  imshow(grayImage),title('2-灰度化');  %imshow(grayImage);  %%%%显示中间状态 灰度化
subplot(2,2,3),  imshow(binaryImage),title('3-二值化');  % imshow(binaryImage);  %%%%显示中间状态  中值滤波 二值化
subplot(2,2,4),  imshow(srcImage),title('4-车道识别');

hold on;%%%%保持显示


% line_length_thred =100; %车道线长度阈值
line_length_thred =0.5; %车道线长度阈值
% slope_thred = 0.3;%车道线斜率阈值
slope_thred = 0.2;%车道线斜率阈值

for k=1:length(lines)
    xy=[lines(k).point1;lines(k).point2];%线段两个端点的坐标
    
    line_length=sqrt(  (xy(1,1)-xy(2,1))^2 + (xy(1,2)-xy(2,2))^2  );%线段长度
    %根据线段 长度 筛除一部分线段
    if(line_length         continue;%continue主要用于结束本次循环,跳过continue语句后面的代码,然后继续执行下一次循环
    end

    slope = (xy(1,2)-xy(2,2))/(xy(1,1)-xy(2,1)); %斜率
     %根据线段 斜率 筛除一部分线段
    if(abs(slope)         continue;
    end

    %将满足条件的线段 画在图像上
    xx=[xy(1,1), xy(2,1)];
    yy=[xy(1,2), xy(2,2)];
    plot(xx,yy,'LineWidth',2,'color','green');
    
end


 

 

 

你可能感兴趣的:(Matlab,matlab)