原文:http://blogs.mathworks.com/steve/2006/06/06/batch-processing/
Step 1: Get a list of filenames
If you use the dir function with an output argument, you get back a structure array containing the filenames, as well as other information about each file.
Let's say I want to process all files ending in .jpg:
files = dir('*.jpg')
Let's look at the details of the
files struct array for a couple of these files.
files(1)
files(end)
Step 2: Determine the processing steps to follow for each file
There are four basic steps to follow for each file:
- Read in the data from the file.
- Process the data.
- Construct the output filename.
- Write out the processed data.
Here's what my read and processing steps looked like:
rgb = imread('IMG_0175.jpg'); % or rgb = imread(files(1).name);
rgb = rgb(1:1800, 520:2000, :);
rgb = imresize(rgb, 0.2, 'bicubic');
You have many options to consider for constructing the output filename. In my case, I wanted to use the same name but in a subfolder:
output_name = ['cropped\' files(1).name] % Use fullfile instead if you want
% multiplatform portability
You might use something like this if you want to change image formats.
input_name = files(1).name
[path, name, extension] = fileparts(input_name)
output_name = fullfile(path, [name '.tif'])
Step 3: Put everything together in a for loop
Here's my complete batch processing loop:
files = dir('*.JPG');
for k = 1:numel(files)
rgb = imread(files(k).name);
rgb = rgb(1:1800, 520:2000, :);
rgb = imresize(rgb, 0.2, 'bicubic');
imwrite(rgb, ['cropped\' files(k).name]);
end