Main Content

Convert Between Image Sequences and Video

This example shows how to convert between video files and sequences of image files using VideoReader and VideoWriter.

The sample file shuttle.avi contains 121 frames. Convert the frames to image files using VideoReader and the imwrite function. Then, convert the image files to an AVI file using VideoWriter.

Setup

Create a temporary working folder to store the image sequence.

workingDir = tempname;
mkdir(workingDir)
mkdir(workingDir,"images")

Create VideoReader Object

Create a VideoReader object to use for reading frames from the sample file.

shuttleVideo = VideoReader("shuttle.avi");

Create Image Sequence

Loop through the video, reading each frame into a width-by-height-by-3 array named img. Write each image to a JPEG file with a name in the form N.jpg, where N is the three-digit frame number.

i = 1;

while hasFrame(shuttleVideo)
   img = readFrame(shuttleVideo);
   filename = sprintf("%03d",i)+".jpg";
   fullname = fullfile(workingDir,"images",filename);
   imwrite(img,fullname)    % Write to a JPEG file (001.jpg, 002.jpg, ..., 121.jpg)
   i = i+1;
end

Find Image Filenames

Find all the JPEG filenames in the images folder. Convert the set of image names to a cell array.

imageNames = dir(fullfile(workingDir,"images","*.jpg"));
imageNames = {imageNames.name}';

Create New Video with Image Sequence

Create a VideoWriter object, which creates a Motion-JPEG AVI file by default.

outputVideo = VideoWriter(fullfile(workingDir,"shuttle_out.avi"));
outputVideo.FrameRate = shuttleVideo.FrameRate;
open(outputVideo)

Loop through the image sequence, load each image, and then write it to the video.

for i = 1:length(imageNames)
   img = imread(fullfile(workingDir,"images",imageNames{i}));
   writeVideo(outputVideo,img)
end

Finalize the video file.

close(outputVideo)

View Final Video

Create a VideoReader object.

shuttleAvi = VideoReader(fullfile(workingDir,"shuttle_out.avi"));

Create a structure array from the video frames.

i = 1;
while hasFrame(shuttleAvi)
   mov(i) = im2frame(readFrame(shuttleAvi));
   i = i+1;
end

Size a figure based on the width and height of the video, and then play the video one time.

vf = figure(Position=[0 0 shuttleAvi.Width shuttleAvi.Height]);
imshow(mov(1).cdata,Border="tight")
movie(vf,mov,1,shuttleAvi.FrameRate)

Clear VideoReader Objects

Clear the VideoReader objects.

clear shuttleVideo shuttleAvi

Credits

The space shuttle video is courtesy of NASA.

Related Topics

Read Video Files