Vehicle Tracking Model

MATLAB add-on for vehicle detection using a pre-trained SVM model with HOG features. Simple, accurate, and easy to integrate into projects.
27 Downloads
Updated 14 Dec 2024

View License

This MATLAB add-on enables vehicle detection in images using a pre-trained Support Vector Machine (SVM) classifier. The model is trained using Histogram of Oriented Gradients (HOG) features, providing high accuracy and reliable performance. With just a few lines of code, you can easily detect vehicles in images of various formats, including .jfif.
The add-on includes:
  • A pre-trained SVM classifier for vehicle classification.
  • A simple interface for image detection.
  • Customization options for retraining the model with your own dataset.
Ideal for applications in autonomous driving, smart cities, or image analysis, this tool simplifies the integration of vehicle detection into your MATLAB projects.
After downloading unzip the file. Then detect vehicle from image with the following code:
load('vehicleClassifier.mat');
testImage=imread('testImage.jpg'); %Replace image with actual image
targetSize=[128 128];
testImageResized=imresize(testImage,targetSize);
if size(testImageResized,3)==3
testImageGray=rgb2gray(testImageResized);
else
testImageGray=testImageResized;
end
testFeatures=extractHOGFeatures(testImageGray,'CellSize',cellSize);
predictedLabel=predict(classifier,testFeatures);
disp(['The predicted class is: ',char(predictedLabel)]);
figure;
imshow(testImage);
title(['Predicted class: ', char(predictedLabel)]);
To detect vehicle from video:
% Load the trained classifier and parameters
load('vehicleClassifier.mat'); % Contains 'classifier', 'cellSize', 'targetSize'
% Specify the path to your video file
videoFile = 'testVideo.mkv'; % Replace with your video file path
% Create a VideoReader object
videoReader = VideoReader(videoFile);
% Create a VideoWriter object to write the processed video
outputVideoFile = 'processed_video_with_scoreboard.mp4'; % Output video file name
videoWriter = VideoWriter(outputVideoFile, 'MPEG-4');
open(videoWriter);
% Initialize vehicle counts
vehicleCounts = struct('Bus', 0, 'Car', 0, 'Motorbike', 0,'CNG',0,'Rickshaw',0,'Truck',0);
% Define scoreboard position and style
scoreboardPosition = [10, 10]; % Top-left corner of the scoreboard
scoreboardFontSize = 14;
scoreboardBoxColor = 'yellow';
scoreboardTextColor = 'black';
% Process each frame
while hasFrame(videoReader)
% Read the next frame
frame = readFrame(videoReader);
% Convert the frame to grayscale
grayFrame = rgb2gray(frame);
% Enhance contrast if necessary
grayFrame = histeq(grayFrame);
% Detect edges using the Canny method
edges = edge(grayFrame, 'Canny');
% Dilate edges to connect adjacent edges
se = strel('rectangle', [5, 5]);
dilatedEdges = imdilate(edges, se);
% Fill holes to create solid shapes
filledRegions = imfill(dilatedEdges, 'holes');
% Remove small objects (noise)
cleanImage = bwareaopen(filledRegions, 1000); % Adjust threshold as needed
% Label connected components
[labelsMatrix, numObjects] = bwlabel(cleanImage);
% Measure properties of image regions
stats = regionprops(labelsMatrix, 'BoundingBox', 'Area');
% Loop through each detected region
for i = 1:numObjects
% Filter out regions that are too small or too large
if stats(i).Area > 2000 % Adjust area threshold as needed
bbox = stats(i).BoundingBox;
% Crop the detected region from the grayscale frame
detectedRegion = imcrop(grayFrame, bbox);
% Resize to match the size used during training
detectedRegion = imresize(detectedRegion, targetSize);
% Extract HOG features
hogFeatures = extractHOGFeatures(detectedRegion, 'CellSize', cellSize);
% Predict the class label
predictedLabel = predict(classifier, hogFeatures);
labelStr = char(predictedLabel);
% Increment the corresponding count
if isfield(vehicleCounts, labelStr)
vehicleCounts.(labelStr) = vehicleCounts.(labelStr) + 1;
else
vehicleCounts.(labelStr) = 1;
end
% Draw bounding box and label on the frame
frame = insertShape(frame, 'Rectangle', bbox, 'Color', 'green', 'LineWidth', 2);
frame = insertText(frame, [bbox(1), bbox(2)-15], labelStr, 'FontSize', 12, 'BoxColor', 'yellow', 'TextColor', 'black');
end
end
% Update the scoreboard text
scoreboardText = sprintf('Bus: %d\nCar: %d\nMotorbike: %d\nCNG: %d\nRickshaw: %d\nTruck: %d', ...
vehicleCounts.Bus, vehicleCounts.Car, vehicleCounts.Motorbike, vehicleCounts.CNG, vehicleCounts.Rickshaw, vehicleCounts.Truck);
% Add the scoreboard to the frame
frame = insertText(frame, scoreboardPosition, scoreboardText, ...
'FontSize', scoreboardFontSize, ...
'BoxColor', scoreboardBoxColor, ...
'TextColor', scoreboardTextColor, ...
'BoxOpacity', 0.6);
% Display the processed frame
imshow(frame);
drawnow;
% Write the processed frame to the output video
writeVideo(videoWriter, frame);
end
% Close the video writer
close(videoWriter);
% Display the vehicle counts
disp('Total Vehicle Counts:');
disp(vehicleCounts);
This is primary versionof our model . We just detect with Bus, Car, CNG , Motorbike, Rickshaw, Truck with our model. But you can detect more type by adding folder like "Ambulance" or etc and download image of ambulance in the folder. Then run the dataStore.m file and your model will be updated. You can reduce the error of detecting vehicle by adding more sample image in respective folder.
In the time of running dataStore.m you may face some error . Here are some prerequisite to run smoothly
  • MATLAB (Version 2020a or later): Ensure you are using a compatible version of MATLAB.
  • Required Toolboxes:
Computer Vision Toolbox: For image processing, feature extraction, and visualization.
Statistics and Machine Learning Toolbox: Required for the fitcecoc function to train the SVM classifier.
License
This project is licensed under the MIT License.
MIT License
Copyright (c) 2024 - MD. Salehin Islam
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
To reach out me:-
Thanks
Salehin
from Bangladesh

Cite As

MD SALEHIN (2025). Vehicle Tracking Model (https://www.mathworks.com/matlabcentral/fileexchange/176863-vehicle-tracking-model), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2023a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

VehicleDetectingModel

Version Published Release Notes
1.2.7

Improved UI in testVehicle.m file

1.1.0

Improved accuracy and increased the type of vehicle.

1.0.0