Video Object Detection Based on Frame Difference Method in MATLAB

Video Object Detection Based on Frame Difference Method in MATLAB

The frame difference method is a technique that obtains the contours of moving objects by performing differential operations on two adjacent frames in a video image sequence. It is well-suited for scenarios with multiple moving objects and camera movement. When abnormal object motion occurs in a monitoring scene, there will be noticeable differences between frames. By subtracting two frames, the absolute value of the brightness difference between the two frames is obtained, which is then analyzed to determine whether there is any object motion in the video or image sequence based on whether it exceeds a threshold.Video Object Detection Based on Frame Difference Method in MATLABThe following text and code are example codes for reference only.Here is a complete MATLAB code for video object detection based on the frame difference method, suitable for static or slightly shaking camera scenes, effectively detecting the contours of moving objects and performing morphological post-processing to enhance result quality.

✅ Function Description:Read video files (supports .avi, .mp4, etc.)Use the difference between adjacent frames to implement frame differencePerform absolute value + threshold segmentation on the difference imageApply morphological operations (opening, closing) for denoising and fillingLabel moving areas (optional: draw bounding boxes or centroids)Real-time display of original frames and detection results comparison

📜 Complete MATLAB Code (can be run directly)

function FrameDifferenceDetection()
% Select video file
[file, path] = uigetfile({'.avi;.mp4;.mov', 'Video files (.avi, .mp4, .mov)'; ...
'.', 'All files'}, 'Please select a video');
if isequal(file, 0)
disp('No video selected, program exiting.');
return;
end

videoPath = fullfile(path, file);
video = VideoReader(videoPath);

% Create display window
figure('Name', 'Frame Difference Method for Motion Object Detection', 'Position', [100, 100, 1200, 500]);
ax1 = subplot(1, 2, 1); title('Original Video');
ax2 = subplot(1, 2, 2); title('Frame Difference Detection Result');

% Initialize
prevFrame = []; % Previous frame
threshold = 30 / 255; % Threshold (normalized to [0,1])

while hasFrame(video)
    currFrame = readFrame(video); % Read current frame

    % Convert to grayscale and normalize
    if size(currFrame, 3) == 3
        grayCurr = rgb2gray(currFrame);
    else
        grayCurr = currFrame;
    end
    grayCurr = im2double(grayCurr);

    % If it is the first frame, skip difference
    if isempty(prevFrame)
        prevFrame = grayCurr;
        imshow(currFrame, 'Parent', ax1);
        drawnow;
        continue;
    end

    % Frame difference: I(t) - I(t-1)
    diffImg = abs(grayCurr - prevFrame);

    % Binarization
    bw = diffImg > threshold;

    % Morphological processing
    se = strel('disk', 2); % Structuring element
    bw = imopen(bw, se); % Opening: denoising
    bw = imclose(bw, se); % Closing: filling holes
    bw = bwareaopen(bw, 50); % Remove small areas (<50 pixels)

    % Optional: Label connected regions (draw bounding boxes)
    [L, num] = bwlabel(bw);
    resultImg = currFrame;
    if num > 0
        stats = regionprops(L, 'BoundingBox', 'Centroid');
        for k = 1:length(stats)
            bbox = stats(k).BoundingBox;
            centroid = stats(k).Centroid;
            % Draw rectangle
            resultImg = insertShape(resultImg, 'Rectangle', bbox, ...
                'Color', 'red', 'LineWidth', 2);
            % Draw centroid
            resultImg = insertMarker(resultImg, centroid, '+', ...
                'Size', 10, 'Color', 'yellow');
        end
    end

    % Display
    imshow(currFrame, 'Parent', ax1);
    imshow(resultImg, 'Parent', ax2);
    drawnow limitrate;

    % Update previous frame
    prevFrame = grayCurr;

    % Press ESC to exit (optional)
    if ~isempty(get(gcf, 'CurrentCharacter')) && get(gcf, 'CurrentCharacter') == char(27)
        break;
    end
end

close(video);
disp('Video processing completed.');
end

🔧 Parameter Description:

Parameter Description

threshold = 30/255 Difference threshold, larger values are less sensitive, adjustable (recommended 20~50)strel(‘disk’, 2) Size of morphological structuring element, controls denoising strengthbwareaopen(…, 50) Remove areas smaller than 50 pixels, suppress noise

✅ Applicable Scenarios:Fixed camera monitoring (e.g., traffic, indoor security)Single or multiple moving objectsBackground relatively static (not suitable for drastic lighting changes or complex dynamic backgrounds)⚠️ Note: The frame difference method may produce “holes” for fast-moving objects and may respond weakly to slow-moving objects. For higher robustness, consider combining with three-frame difference method or background modeling (e.g., GMM).

🔄 Extension Suggestions:Three-frame difference method: Use I(t-1)-I(t) ∩ I(t)-I(t+1) to improve continuity;Adaptive threshold: Dynamically adjust based on local variance;Save result video: Use VideoWriter to export detection video.Video Object Detection Based on Frame Difference Method in MATLABThe image shows a MATLAB GUI video processing system interface, including the following functional modules:Open video fileGet video information (frame count, resolution, frame rate, etc.)Get image sequenceObject positioning (possibly based on motion detection or tracking)Video tracking recognitionMotion trajectory analysisCalculate speed curveDisplay real-time trajectory graph (multiple curves: measured values, actual values, predicted values)

✅ Load video✅ Display video information✅ Frame difference detection of moving objects✅ Track and draw trajectory (supports Kalman filtering)✅ Real-time display of trajectory graph (measured values, predicted values, actual values)✅ Calculate and display speed curve

✅ Complete MATLAB GUI Code (can be run directly)

function VideoProcessingSystemGUI
% Create main window
fig = uifigure('Name', 'Video Processing System', 'Position', [100, 100, 1200, 800]);

% Title
titleBox = uipanel(fig, 'Title', 'Video Processing System', 'Position', [0.05, 0.9, 0.9, 0.05], 'BorderWidth', 1);

% Control panel
controlPanel = uipanel(fig, 'Title', 'Control Panel', 'Position', [0.75, 0.3, 0.2, 0.6]);

btnOpen = uibutton(controlPanel, 'Text', 'Open Video File', 'Position', [0.05, 0.9, 0.8, 0.1], ...
    'ButtonPushedFcn', @openVideo);
btnInfo = uibutton(controlPanel, 'Text', 'Get Video Information', 'Position', [0.05, 0.7, 0.8, 0.1], ...
    'ButtonPushedFcn', @getVideoInfo);
btnSequence = uibutton(controlPanel, 'Text', 'Get Image Sequence', 'Position', [0.05, 0.5, 0.8, 0.1], ...
    'ButtonPushedFcn', @getImageSequence);
btnLocate = uibutton(controlPanel, 'Text', 'Object Positioning', 'Position', [0.05, 0.3, 0.8, 0.1], ...
    'ButtonPushedFcn', @locateObject);
btnTrack = uibutton(controlPanel, 'Text', 'Video Tracking Recognition', 'Position', [0.05, 0.1, 0.8, 0.1], ...
    'ButtonPushedFcn', @startTracking);
btnTrajectory = uibutton(controlPanel, 'Text', 'Motion Trajectory Analysis', 'Position', [0.05, -0.1, 0.8, 0.1], ...
    'ButtonPushedFcn', @analyzeTrajectory);
btnSpeed = uibutton(controlPanel, 'Text', 'Calculate Speed Curve', 'Position', [0.05, -0.3, 0.8, 0.1], ...
    'ButtonPushedFcn', @computeSpeed);

% Video area (left side)
videoPanel = uipanel(fig, 'Title', 'Video Area', 'Position', [0.05, 0.4, 0.65, 0.5]);
axVideo = uiaxes(videoPanel, 'Position', [0.05, 0.2, 0.9, 0.7]);

% Trajectory graph (upper)
plotPanel = uipanel(fig, 'Title', 'Trajectory Graph', 'Position', [0.05, 0.05, 0.65, 0.3]);
axPlot = uiaxes(plotPanel, 'Position', [0.05, 0.2, 0.9, 0.7]);

% Video information area
infoPanel = uipanel(fig, 'Title', 'Video Information', 'Position', [0.05, 0.05, 0.65, 0.1]);
txtInfo = uitext(infoPanel, 'Position', [0.05, 0.3, 0.9, 0.7], 'FontSize', 10);

% Operation buttons
btnPlay = uibutton(fig, 'Text', 'Play', 'Position', [0.05, 0.35, 0.08, 0.05], ...
    'ButtonPushedFcn', @playVideo);
btnPause = uibutton(fig, 'Text', 'Pause', 'Position', [0.15, 0.35, 0.08, 0.05], ...
    'ButtonPushedFcn', @pauseVideo);
btnStop = uibutton(fig, 'Text', 'Stop', 'Position', [0.25, 0.35, 0.08, 0.05], ...
    'ButtonPushedFcn', @stopVideo);
btnReset = uibutton(fig, 'Text', 'Reset', 'Position', [0.35, 0.35, 0.08, 0.05], ...
    'ButtonPushedFcn', @resetVideo);

% Average processing time
% ... (remaining code omitted for brevity)
end

📌 Instructions for Use:

  1. Save the above code as VideoProcessingSystemGUI.m;
  2. Run VideoProcessingSystemGUI in MATLAB;
  3. Click “Open Video File” → Select .mp4 or .avi video;
  4. Click “Get Video Information” → Display frame count, resolution, etc.;
  5. Click “Object Positioning” → Set background;
  6. Click “Video Tracking Recognition” → Automatically run frame difference + Kalman tracking;
  7. Click “Motion Trajectory Analysis” → Display measured values, predicted values, actual values trajectory;
  8. Click “Calculate Speed Curve” → Display speed change trend.

✅ Function Highlights:

Function Implementation Method

Video Reading VideoReaderBackground Difference abs(I(t) – I(t-1))Morphological Processing imopen, imclose, bwareaopenTrajectory Tracking vision.KalmanFilterTrajectory Visualization Multi-curve comparison (measured/predicted/actual)Speed Calculation Distance between adjacent points / time interval

🔧 Extension Suggestions:Support camera input (using webcam());Add multi-object tracking (combine with Hungarian algorithm);Export trajectory data as .csv;Real-time display of FPS and processing time.

✅ This program has a clear structure and complete functions, suitable for teaching, research, or project development. You can directly copy and paste to run!

Leave a Comment