foregroundDetector = vision.ForegroundDetector('NumGaussians', 3, 'NumTrainingFrames', 50);
videoReader = VideoReader('VID_20211023_090102.mp4');
frame = readFrame(videoReader);
foreground = step(foregroundDetector, frame);
figure; imshow(frame); title('Video Frame');
figure; imshow(foreground); title('Foreground');
filteredForeground = imopen(foreground, se);
figure; imshow(filteredForeground); title('Clean Foreground');
blobAnalysis = vision.BlobAnalysis('BoundingBoxOutputPort', true, ...
'AreaOutputPort', false, 'CentroidOutputPort', false, 'MinimumBlobArea', 150);
bbox = step(blobAnalysis, filteredForeground);
result = insertShape(frame, 'Rectangle', bbox, 'Color', 'green');
result = insertText(result, [10 10], numCars, 'BoxOpacity', 1, 'FontSize', 14);
figure; imshow(result); title('Detected Cars');
videoPlayer = vision.VideoPlayer('Name', 'Detected Cars');
videoPlayer.Position(3:4) = [650,400];
while hasFrame(videoReader)
frame = readFrame(videoReader);
foreground = step(foregroundDetector, frame);
filteredForeground = imopen(foreground, se);
bbox = step(blobAnalysis, filteredForeground);
result = insertShape(frame, 'Rectangle', bbox, 'Color', 'green');
result = insertText(result, [10 10], numCars, 'BoxOpacity', 1, ...
step(videoPlayer, result);