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

6 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...
directory='F:\Test\S29_FR4_2s_9or5\Mouse3\l3';
sdirectory=dir(directory);
for a=3:size(sdirectory,1)
filename=horzcat(directory, '\', sdirectory(a).name);
filecheck=contains(filename,'.avi') && contains(filename, 'Lever', 'IgnoreCase', true);
if filecheck==1;
v=VideoReader(filename);
frame=[8580,8619,43380,43422]
for b=1:size(frame,1)
f=frame(1,b);
thisframe=read(v,f);
imwrite(thisframe, [directory, '\', '.jpg']);
end
end
end
  2 Comments
Stephen23
Stephen23 on 24 Nov 2021
Edited: Stephen23 on 24 Nov 2021
Rather than that very complicated approach to filtering for particular filenames you should simply specify a suitable filename with wildcards for the DIR command:
P = 'F:\Test\S29_FR4_2s_9or5\Mouse3\l3';
S = dir(fullfile(P,'*Lever*.jpg'));
for a = 1:numel(S)
...
end
Note that assuming that the dot-directories come first is a latent bug in your code and yet is trivially avoided by specifying the name (with wildcards and file extension as required) in the DIR call.
You should use FULLFILE rather than concatenating strings and file separators:
fnm = fullfile(P,S(a).name):
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.

More Answers (0)

Categories

Find more on Images in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!