How can I automate the code to run a series of files in a folder?

2 views (last 30 days)
% Read in Raw Data, change file path to match your computer
vidObj = VideoReader('G:\.shortcut-targets-by-id\1332UW1v7_g1_AsDgTVQW_dgb0LzbQ4Ni\Elizabeth-Data-Analysis-Spring-2021\raw_data\free03082021\free001.avi');
% Prepare to write out clean data for tracking
cleanVid = VideoWriter('G:\.shortcut-targets-by-id\1332UW1v7_g1_AsDgTVQW_dgb0LzbQ4Ni\Elizabeth-Data-Analysis-Spring-2021\clean_data\free03082021\free001clean.avi');
section = read(vidObj, [3500,5100]);% Declare the section of the video that you're going to be using
background = read(vidObj, 3500);% Choose the image that will be used to subtract out the noise
i = 3500;% Start the counter at the first frame
open(cleanVid);% Open the file that you will write to
for i = 3500:5100% Loop through all the frames of the video in the section
currentFrame = read(vidObj, i); % Declare what the current frame is
cleanFrame = imsubtract(currentFrame, background);% Perform the image subtraction of the background from the current
writeVideo(cleanVid, cleanFrame); % Write the clean subtracted frame into the new video
i = i+1; % Increase the frame counter
end
close(cleanVid);
disp('done') % for command window confirmation the script is done
I have a group of files that I would like to clean and subtract out a background image, they are labeled free001,free002,free003, and so on. See file paths above. I have been manually changing the file directories after each run by one number for the next video. The only part of the filepath that needs to change is increasing the free00X number by 1. I am looking for a way to automate this, I cannot understand how to change the read and write location for each video with the dir or for loop. Any help appreciated, thank you.

Accepted Answer

Stephen23
Stephen23 on 22 Jun 2021
Edited: Stephen23 on 22 Jun 2021
P = 'G:\.shortcut-targets-by-id\1332UW1v7_g1_AsDgTVQW_dgb0LzbQ4Ni\Elizabeth-Data-Analysis-Spring-2021';
N = 64; % total number of videos: change to suit your files!
for k = 1:N
% Read in Raw Data, change file path to match your computer
FnR = sprintf('free%03d.avi',k);
vidObj = VideoReader(fullfile(P,'raw_data','free03082021',FnR));
% Prepare to write out clean data for tracking
FnC = sprintf('free%03dclean.avi',k);
cleanVid = VideoWriter(fullfile(P,'clean_data','free03082021',FnC));
... the rest of your code
... (excluding this superfluous line: i = i+1; % Increase the frame counter,
... because the FOR loop already increments the counter that line does nothing)
end

More Answers (0)

Community Treasure Hunt

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

Start Hunting!