MATLAB code for vedio edge detection

ANPHY JOSE · Mar 2, 2023 · 2K views
Question
hello sir, I need your help in matlab code for video edge detection .It's very urgent.please send the code.  
Expert Answer
Profile picture of Prashant Kumar
Prashant Kumar PhD Expert
Answered Aug 15, 2026

Here's a simple MATLAB code example for performing edge detection on a video. The code uses the Canny edge detection method to process each frame of the video.

matlab
% Load the video file
videoFile = 'your_video_file.mp4';
videoReader = VideoReader(videoFile);

% Create a video writer to save the output
outputVideo = VideoWriter('output_video.avi');
open(outputVideo);

while hasFrame(videoReader)
    % Read the next frame
    frame = readFrame(videoReader);
    
    % Convert the frame to grayscale
    grayFrame = rgb2gray(frame);
    
    % Perform edge detection using the Canny method
    edgeFrame = edge(grayFrame, 'Canny');
    
    % Convert logical image to uint8 for video writing
    edgeFrame = uint8(edgeFrame) * 255;
    
    % Write the processed frame to the output video
    writeVideo(outputVideo, edgeFrame);
end

% Close the video writer
close(outputVideo);

disp('Edge detection video has been saved as output_video.avi');

Steps Explained:

  1. Load the Video: Use VideoReader to load the input video file.

  2. Process Each Frame: Loop through each frame of the video, convert it to grayscale, and apply the Canny edge detection method using the edge function.

  3. Save the Output: Write each processed frame to a new video file using VideoWriter.

Replace 'your_video_file.mp4' with the path to your video file. This code will process the video and save the edge-detected version as output_video.avi.

Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!