How to introduce for loop index in filename when using imwrite function?

7 views (last 30 days)
I'm very new to Matlab, so I'm sorry if this is too basic... I'm trying to figure out how to save all specified frames of a video (I usually don't have only 4 frames; I have more than 100...), giving them different names, preferable containing either the b variable corresponding to that loop or the corresponding frame number. How do I introduce that in the "imwrite..." line below? The way it is written now, it only saves the last frame, of course...
for a=3:size(sdirectory,1)
filename=horzcat(directory, '\', sdirectory(a).name);
filecheck=contains(filename,'.avi') && contains(filename, 'Lever', 'IgnoreCase', true);
if filecheck==1;
for b=1:size(frame,1)
imwrite(thisframe, [directory, '\', '.jpg']);
Daniela Pereira
Daniela Pereira on 25 Nov 2021
Thank you very much! These are really helpful suggestions, not only to solve this particular problem but to improve the code.

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 24 Nov 2021
Try this:
baseFileName = sprintf('Frame %4.4d.jpg', a);
fullFileName = fullfile(directory, baseFileName);
imwrite(thisframe, fullFileName);
If you can at all avoid it, don't use JPG images. They change your image values and can create bad artifacts. Use a .PNG extension instead.
Adapt as needed, like put another prefix in there instead of "Frame", or use 3.3d instead of 4.4d if you know you'll never have more than a thousand frames.
  1 Comment
Daniela Pereira
Daniela Pereira on 24 Nov 2021
Thank you, it worked (substituting a above by b). And thanks for the other suggestions :)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!