【课题】基于matlab行驶车辆检测计数【含Matlab源码 627期】

一、简介

基于matlab行驶车辆检测计数:读入待处理视频,用于色彩空间转换、检测出包含汽车运动的图像块、用高斯混合模型检测背景、对检测出的运动车辆进行框画、标注检测到车辆的个数用于显示结果。

二、源代码

clear;close all;
SE = strel('rectangle',[10 10]); %注意:结构元素必须具有适当的大小
BW1=imread('test5.jpg');
subplot(221);imshow(BW1);title('原图');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%添加
GRAY=rgb2gray(BW1); %灰度图像1
h=fspecial('average',9);
GRAY=uint8(round(filter2(h,GRAY))); %进行均值滤波
subplot(222);imshow(GRAY);title('均值滤波');
GRAY = imcrop(GRAY,[10 20 542 355]);   %裁剪
GRAY=double(GRAY); %转换为double类型
[Gx,Gy]=gradient(GRAY); % 计算梯度
G=sqrt(Gx.*Gx+Gy.*Gy); % 水平垂直差分
J=GRAY; 
K=find(G<2); %指定灰度级
J(K)=0;
subplot(223);imshow(J);title('锐化');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
BW2=imdilate(J,SE);%膨胀
BW3 = imfill(BW2,'holes'); %填充
BW4=imerode(BW3,SE);%腐蚀
I=im2bw(BW4);
subplot(224);imshow(I);title('目标块');
%====形态特征值计算===%
A=bwarea(I); % 计算目标的面积
I1=edge(I,'canny',0.7);
[L, num]=bwlabel(I1,8);%存放提取的目标矩阵和数目
STATS = regionprops(L,'BoundingBox');
% 存放经过筛选以后得到的所有矩形块  
n = 1; 
wh=zeros(1,num); 
for i=1:num
    box = STATS(i).BoundingBox;  %图像的长宽
    x = box(1);    %矩形坐标x  
    y = box(2);    %矩形坐标y  
    w = box(3);    %矩形宽度w  
    h = box(4);    %矩形高度h 
    wh(1,i)=w*h;
    ux = ceil(x);  %取整
    uy = ceil(y);  
    if ux > 1  
         ux = ux - 1;  
     end  
     if uy > 1  
        
     end  
     %result(n,:) = [ux uy w h];
         R=zeros(h,w);
         G=zeros(h,w);
         B=zeros(h,w);
        for j=1:w
            for ii=1:h
                R(ii,j)=BW1(ii+uy-1,j+ux-1,1);
                
                B(ii,j)=BW1(ii+uy-1,j+ux-1,3);
            end
        end
       % r(1,n)=mean(mean(R))
       % g(1,n)=mean(mean(G))
       % b(1,n)=mean(mean(B))
       % n = n+1;
      
        if(r(1,i)>130&&g(1,i)<130&&b(1,i)<130)
            disp('检测出车辆是红色')
        elseif(r(1,i)<130&&g(1,i)>130&&b(1,i)<130)
            disp('检测出车辆是绿色')
        elseif(r(1,i)<130&&g(1,i)<130&&b(1,i)>130)
            disp('检测出车辆是蓝色')
        elseif(r(1,i)<80&&g(1,i)<80&&b(1,i)<80)
            disp('检测出车辆是黑色')
        elseif(r(1,i)>170&&g(1,i)>170&&b(1,i)>170)
            disp('检测出车辆是白色')
        else
            disp('检测出车辆是其他色')
        end
end
% 创建系统对象,用于显示结果
sz = get(0,'ScreenSize');
pos = [20 sz(4)-300 200 200];
hVideoOrig = vision.VideoPlayer('Name', 'Original', 'Position', pos);
pos(1) = pos(1)+220;  %在右侧建立下一个视窗
hVideoFg = vision.VideoPlayer('Name', 'Foreground', 'Position', pos);
pos(1) = pos(1)+220;
hVideoRes = vision.VideoPlayer('Name', 'Results', 'Position', pos);
line_row = 23; % 定义感兴趣区域(ROI)
% 以下的程序段为对输入的视频图像进行处理
while ~isDone(hvfr)
    image = step(hvfr);      % 读入视频的每一帧
    y = step(hcsc, image);    % 将彩色图像转换成灰度图像
% 采用自动白平衡算法去除灰度突变
    y = y-mean(y(:));
    fg_image = step(hfdet, y); % 检验背景
    % 采用数学形态学,在前景图像中检测变化的联通图像块区域的面积
    [area, bbox] = step(hblob, fg_image);
    image_out = image;
 
 
end

三、运行结果

在这里插入图片描述
在这里插入图片描述

四、备注

完整代码或者代写添加QQ 1564658423

猜你喜欢

转载自blog.csdn.net/TIQCmatlab/article/details/115220819