Extracting and saving frames from a video with automatic number '0001,0002,0003' instead of 1,2,3 etc
10 views (last 30 days)
Show older comments
Andrew Palmer
on 16 Aug 2022
Commented: Andrew Palmer
on 17 Aug 2022
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
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=sprintf('%04d', 1000)
y=sprintf('%05d', 98)
y=sprintf('%06d', 2357)
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)
Accepted Answer
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!