Batch processing
23-Jun-2015 update: See the new Image Batch Processor App (added to R2015a) and my blog post about it.
A couple of months ago I was working with a bunch of pictures I had taken at home. I had about 40 of them, and I needed to crop and resize them all the same way. Naturally, I wrote a MATLAB script to do it.
This experience reminded me that customers sometimes ask "How do I use the Image Processing Toolbox to do batch processing of my images?" Really, though, this isn't a toolbox question; it's a MATLAB question. In other words, the basic MATLAB techniques for batch processing apply to any domain, not just image processing.
Contents
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')
files = 42x1 struct array with fields: name date bytes isdir
The files struct array has 42 elements, indicating that there are 42 files matching "*.jpg" in the current directory. Let's look at the details for a couple of these files.
files(1)
ans = name: 'IMG_0175.jpg' date: '12-Feb-2006 10:49:30' bytes: 962477 isdir: 0
files(end)
ans = name: 'IMG_0216.jpg' date: '12-Feb-2006 11:09:10' bytes: 1004842 isdir: 0
Step 2: Determine the processing steps to follow for each file
There are four basic steps to follow for each file:
1. Read in the data from the file.
2. Process the data.
3. Construct the output filename.
4. 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
output_name = cropped\IMG_0175.jpg
Here's another example of output name construction. You might use something like this if you want to change image formats.
input_name = files(1).name
input_name = IMG_0175.jpg
[path, name, extension] = fileparts(input_name)
path = '' name = IMG_0175 extension = .jpg
output_name = fullfile(path, [name '.tif'])
output_name = IMG_0175.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
Comments
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.