REAL-TIME FACE DETECTION AND COUNTING USING MATLAB

Version 1.0.0 (8.89 KB) by Asif Faisal
A flexible dual-mode face detection system is implemented, allowing users to select between live webcam detection or static image processin
1 Download
Updated 11 May 2025

View License

clc;
clear;
close all;
% Mode Selection
choice = menu('Select Mode','Live Webcam Detection','Detect from Image');
% Create a face detector object
faceDetector = vision.CascadeObjectDetector();
if choice == 2
%Image mode
[file, path] = uigetfile({'*.jpg;*.png;*.bmp'}, 'Select an image');
if isequal(file, 0)
disp('No image selected.');
return;
end
img = imread(fullfile(path, file));
bboxes = step(faceDetector, img);
numFaces = size(bboxes, 1);
for i = 1:numFaces
label = sprintf('Face %d', i);
img = insertObjectAnnotation(img, 'rectangle', bboxes(i,:), label);
end
img = insertText(img, [10, 10], ['Total Faces: ', num2str(numFaces)], ...
'FontSize', 18, 'BoxColor', 'green', 'BoxOpacity', 0.6);
figure('Name','Face Detection - Image','NumberTitle','off');
imshow(img);
elseif choice == 1
%live web cam mode
cam = webcam();
figure('Name','Live Face Detection Counter','NumberTitle','off');
while true
frame = fliplr(snapshot(cam)); %fix mirror issue
bboxes = step(faceDetector, frame);
numFaces = size(bboxes, 1);
for i = 1:numFaces
label = sprintf('Face %d', i);
frame = insertObjectAnnotation(frame, 'rectangle', bboxes(i,:), label);
end
labelCount = ['Total Faces: ', num2str(numFaces)];
frame = insertText(frame, [10 10], labelCount, 'FontSize', 18, ...
'BoxColor', 'green', 'BoxOpacity', 0.6);
imshow(frame);
% Exit on key press
if ~isempty(get(gcf,'CurrentCharacter'))
break;
end
drawnow;
end
% Clean up
clear cam;
close all;
else
disp('No option selected. Exiting.');
end

Cite As

Asif Faisal (2025). REAL-TIME FACE DETECTION AND COUNTING USING MATLAB (https://www.mathworks.com/matlabcentral/fileexchange/181123-real-time-face-detection-and-counting-using-matlab), MATLAB Central File Exchange. Retrieved .

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

Inspired by: Face Detection using Viola-Jones

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes
1.0.0