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

14 次查看(过去 30 天)
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 个评论
Dyuman Joshi
Dyuman Joshi 2022-8-16
编辑:Dyuman Joshi 2022-8-16
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)

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2022-8-16
编辑:Stephen23 2022-8-16
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.

更多回答(0 个)

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by