Open In App

How To Create Video From An Image Using MATLAB?

Improve
Improve
Like Article
Like
Save
Share
Report

MATLAB is a high-performance language that is used for manipulating matrices, performing technical computations, graph plottings, etc. It stands for Matrix Laboratory. With the help of this software, we can create videos from images. 

STEPS:

Step 1. Bring the images to the folder where we are writing Matlab commands. Here we have three images namely image1,image2, and image3. Below Folder contents before video creation:

 

Step 2. Load the images to a cell array of 3*1 using the below written Matlab Commands. imread is used to read the image from the file.

Matlab




% load the images stored 
photos   = cell(3,1);
photos{1} = imread('image1.png');
photos{2} = imread('image2.png');
photos{3} = imread('image3.png');


 

Step 3. Create the video using the VideoWriter command and save it inside a variable. Here we have created a video named output.mp4 which is stored in a variable video file. The frame rate of the video file is set to 1.

Matlab




% create the videofile with 1 fps
videofile = VideoWriter('output.mp4','MPEG-4');
videofile.FrameRate = 1;


 

Step 4. Now we’ll set the seconds per image i.e for how many seconds the images will appear. E.g. here image1 will appear for 2 sec, image2 for 3 sec, and imag3 for 4 sec. Hence the total video will be of length 9 seconds.

Matlab




% set the seconds per image
secperImg = [2 3 4];


 

Step 5. Now to write the images to the video file, we’ll open the video file. With the help of for loops, we’ll convert images to frames and write photos to video files using the below-written Matlab commands. Then we’ll end the for loops. Also, we should always close a file, so we’ll close the video file.

Matlab




% open the videofile
open(videofile);
% write the frames to the video
for i=1:length(photos)
    % convert the image to a frame
    frame = im2frame(photos{i});
    for v=1:secperImg(i) 
        writeVideo(videofile, frame);
    end
end
% close the videofile
close(videofile);


 

Step 6. The video file named output.mp4 has now been created in the folder where the Matlab commands are being written. Here is the screenshot.

Output:

Folder Contents after video creation:

 



Last Updated : 11 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads