MATLAB Code For Detecting and Counting Cars Using Gaussian Mixture Models

by admin in , , on July 26, 2020

This code shows how to detect and count cars in a video sequence using a foreground detector based on Gaussian mixture models (GMMs).


Detecting and counting cars can be used to analyze traffic patterns. Detection is also a first step prior to performing more sophisticated tasks such as tracking or categorization of vehicles by their type.

This code shows how to use the foreground detector and blob analysis to detect and count cars in a video sequence. It assumes that the camera is stationary. The example focuses on detecting objects. To learn more about tracking objects, see the example titled Motion-Based Multiple Object Tracking.

Step 1 – Import Video and Initialize Foreground Detector

Rather than immediately processing the entire video, the example starts by obtaining an initial video frame in which the moving objects are segmented from the background. This helps to gradually introduce the steps used to process the video.

The foreground detector requires a certain number of video frames in order to initialize the Gaussian mixture model. This example uses the first 50 frames to initialize three Gaussian modes in the mixture model.

After the training, the detector begins to output more reliable segmentation results. The two figures below show one of the video frames and the foreground mask computed by the detector.

Step 2 – Detect Cars in an Initial Video Frame

The foreground segmentation process is not perfect and often includes undesirable noise. The example uses a morphological opening to remove the noise and to fill gaps in the detected objects.

Next, find bounding boxes of each connected component corresponding to a moving car by using vision.BlobAnalysis object. The object further filters the detected foreground by rejecting blobs which contain fewer than 150 pixels.

To highlight the detected cars, we draw green boxes around them.

The number of bounding boxes corresponds to the number of cars found in the video frame. Display the number of found cars in the upper left corner of the processed video frame.

Step 3 – Process the Rest of Video Frames

In the final step, we process the remaining video frames.

The output video displays the bounding boxes around the cars. It also displays the number of cars in the upper left corner of the video.

See the Video:

Click here.

Recommended Codes:

0 Sale

Share Now!

Release Information

  • Price


  • Released

    July 26, 2020

  • Last Updated

    July 26, 2020

  • File Included

    Matlab Files with Video

  • File Size

    24 Mb

  • Compatible With

    Matlab R19

Share Your Valuable Opinions