MATLAB: How to extract and save frames in a video ?

frame extractionframe readingvideo frames

I am using the following code to read and extract entire frames of a video, but problem is the frames are stored in "multi" as shown in the attached image. It is not stored as 1.jpg, 2.jpg, 3.jpg….. .How to resolve this problem. or tell me how can we extract and store entire frames and how to use it in any for loop.
clc;
clear all;
close all;
tic;
vid=VideoReader('I:\testing\video1.avi');
numFrames = vid.NumberOfFrames;
n=numFrames;
for i = 1:1:n
frames = read(vid,i);
imwrite(frames,['I:\testing\abrupt\' int2str(i), '.jpg']);
end
multi = dir('I:\testing\abrupt\*.jpg*');
for i = 1:1:length(multi)
--------------
--------------
end

Best Answer

The shown code creates the file "1.jpg", "2.jpg" and so on. After getting the file names by dir they are ordered alphabetically, which is not the original order. Solve this by:
Folder = 'I:\testing\abrupt\';
for iFrame = 1:n
frames = read(vid, iFrame);
imwrite(frames, fullfile(Folder, sprintf('%06d.jpg', iFrame)));
end
FileList = dir(fullfile(Folder, '*.jpg'));
for iFile = 1:length(FileList)
aFile = fullfile(Folder, FileList(iFile).name);
img = imread(aFile);
end
fullfile cares about file separators. Now changing the work folder requires a single change in the code only.
"iFile" and "iFrame" is more descritpive than "i", which might shadow the imaginary unit also.
Related Question