Extracting and saving frames from a video with automatic number '0001,0002,0003' instead of 1,2,3 etc

23 views (last 30 days)
I'm writing a code to analyse videos, so am extracting the frames and saving them to a folder before putting them into the main code for analysis of the frames. My issue is that the frames are being numbered '1.jpg, 2.jpg, 3.jpg' etc in the folder they are saved to. This means that when I come to analysing the frames, the processing order is wrong. For example, '12.jpg' is analysed before '2,jpg' due to the '1' being first. I overcame this when there were less than 100 frames by just renaming the first 9 to '01.jpg, 02.jpg', however this code could be used for videos for more than 1000 frames, so ideally I need them to save as '0001.jpg' etc. Is there a way to do this, or is the problem with the way my next code is reading the frames in the wrong order and there is a way to change this? I have attached the code I'm using to extract and save the frames below. In a relevant but unrelated question, is there any need to save the frames at all, or could I extract them at the start of my main script for analysis straight away, since the only important result is that at the end of analysis?
v=VideoReader("Video1.mp4");
vid=read(v);
%Number of frames
frames=v.NumFrames;
%Save frames in file format jpg
ST='.jpg';
for x = 1:frames
Sx=num2str(x);
Strc=strcat(Sx, ST);
Vid=vid(:,:,:,x);
%Choose folder name below
cd Frames
%exporting frames
imwrite(Vid,Strc);
cd ..
end
  1 Comment
Dyuman Joshi
Dyuman Joshi on 16 Aug 2022
Edited: Dyuman Joshi on 16 Aug 2022
In the case of saving them
Depending upon the number of zeros you want to put
y=sprintf('%04d', 2)
y = '0002'
y=sprintf('%04d', 1000)
y = '1000'
y=sprintf('%05d', 98)
y = '00098'
y=sprintf('%06d', 2357)
y = '002357'
The non-zero integer refers to the total number of digits that will be displayed and the remaining spaces other than the number are filled by 0 (indicated by 0 after % sign)

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 16 Aug 2022
Edited: Stephen23 on 16 Aug 2022
V = VideoReader("Video1.mp4");
for k = 1:V.NumFrames
A = readFrame(V);
F = sprintf('%05d.jpg',k);
imwrite(A,fullfile('.','Frames',F))
end
Use absolute/relative filenames rather than slow and difficult-to-debug CD.

More Answers (0)

Products


Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!