Steve on Image Processing

Batch processing 72

Posted by Steve Eddins,

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


Get the MATLAB code

Published with MATLAB® 7.2

72 CommentsOldest to Newest

Hi Steve
I am trying to run part of your for loop for batch processing a folder of 52 images. The only part I am interested in is the
reading a batch of images in. That is I want to extract area of an object as opposed to cropping. So I started with the beginning of your code
files = dir(‘F:\EPD Validation Study\Lab Processing from Field Trip 221107\Boags A\greater than 2\4\Boags 4 Lab JPGS Cropped\*.jpg’)

for k = 1:numel(files)
rgb = imread(files(k).name)
end

but I receive an error message “??? Error using ==> imread at 315
File “R0010864.JPG” does not exist.”

R0010864.jpg is the first image file in the folder “Boags 4 Lab JPGS Cropped”.
I am not sure what I am doing wrong. These images are rgb and are large in size (2000 x 2000 pix)and are being stored on an external hard drive.
I would appreciate any helpful suggestions/solutions you might have.
Thanks
Lucy

Lucy—If you look at files(k).name, you’ll see that it doesn’t include the full path. You either need to modify files(k).name to prepend the full path, or add the image directory to the MATLAB path, or make that directory your working directory.

Thanks for your help Steve. I shifted my images into the current (working) directory and used the code listed below:

files = dir(‘*.JPG’);
for k = 1:(numel(files));
rgb = imread(files(k).name)
end

and I received the following error message:

??? Error using ==> imagesci\private\readjpg
Too many input arguments.

Error in ==> imread at 389
[X, map] = feval(fmt_s.read, filename, extraArgs{:});

This appears to be a syntax error that may be associated with the wrong file format? (my image is class unit 8 it is not an indexed color map). But I also initially though that this loop would read all images into the workspace (at once) but I have since realized that this cannot be the case as there is only a single variable rgb. Therefore each image must be read in one at a time and once the algorithm is applied to the image (or any other functions in the for loop) it will move onto the next image file in the directory. Am I on the right page or have I misunderstood what this code is doing?

Lucy—I don’t see any problem with your code, except that you left off the semicolon on the imread line. That will cause the pixel values (all of them!) to display in the command window. I recommend that you use the debugger to help with your debugging problem. Single-step through the code, and in particular step into imread. Examine the input arguments to imread to make sure they are what you expect. And yes, your loop (once debugged) will read all the images into the same variable, one at a time. If that’s not what you want, consider using a cell array instead.

Hi Steve,

can I import a big number of MODIS images in HDF-EOS format whithout using HDF-toolbox?
Thank in advance, Manu

Manu—MATLAB supports HDF-EOS import and export via the functions hdfgd, hdfpt, hdfsw. I don’t know what you mean by “HDF Toolbox.” There’s no MathWorks product with that name.

Thanks so much Steve.You are simply the best.I knew the problem was simple but just did not know where to look for.I googled “matlab code to read all images in a folder” and got the best result.its quite surprising to see that the crux of this problem is just one line of code, namely, “files = dir(‘*.JPG’);”.

Hi Steve and everyone,
I came across Steve’s posting regarding batch processing.
However, I have tried the code you supplied but cannot go past the imread() statement.
Here is my practice code:

files = dir(‘*.JPG’);
for k = 1:(numel(files));
image = imread(files(k).name);
newImage = imresize(image, 0.5);
imwrite(newImage, [‘NewImage\’, files(k).name,]);
end
and this is the error I get:
??? Error using ==> imwrite
Can’t open file “NewImage\DSCF1639.JPG” for writing.
You may not have write permission.

Error in ==> firstProcessing at 14
imwrite(newImage, [‘NewImage\’, files(k).name,])

??? Error using ==> imwrite
Can’t open file “NewImage\DSCF1639.JPG” for writing.
You may not have write permission.

Error in ==> firstProcessing at 14
imwrite(newImage, [‘NewImage\’, files(k).name,])

What I want to attempt to do is to read over 200 images that are located in a folder called “Images”.
Then I want to resize the images and do image processing on each of these images. Then I want to store each image file in another folder called “ProcessedImages”. However, I want each image’s name to change to a new name, say image1.jpg.

Help in this regard will be very much appreciated.

Silver

Silver—From the error message, I’d guess that the folder called NewImage doesn’t exist before the call to imwrite. The error message says it all: “Can’t open file NewImage\foobar.jpg for writing. You may not have write permission.” That can happen because the folder doesn’t exist, or it does exist and you don’t have write permission to it, or you do have write permission to the folder but not to the file foobar.jpg that’s already in it.

hi steve,

I am trying to batch a sequence of images using the following code:

for k = 1:numel(files)
rgb = imread(files(k).name);
imwrite(rgb, [files(k).name], ‘png’);
end

I want to use the imwrite to save the output. At the same time, I want to save the file in png format instead of jpeg.
But I have trouble with assigning the index for imwrite.

Pak—You haven’t given me enough information to answer your question. What does happen when you run your code? An error message, unexpected behavior, or something else? Also, do you know that your code will just write over the original file with the same name, including the .jpg extension? You might want to look at the fileparts function so that you can construct a new filename with the appropriate extension.

Hi Steve,

There is no error message nor generating new file type. I guess my previous code wrote over the original files as you stated.
I tried this

imwrite(rgb,[‘test’ files(k).name ‘.png’]);

It seems to work but the output file name is strange.
my output filename is like this:
testname0.jpeg.png

It is the file extension I wanted (that’s png) but how do I cancel the .jpeg?

Pak—The output file name you are getting is exactly what you instructed imwrite to do. In your code, you are concatenating ‘.png’ onto the end of the original file name. As I mentioned in my previous comment, I recommend that you use the fileparts function to help construct a new file name.

HI Steve,

I am new to MATLAB, and am trying to process some matrices, using the batch commands, roughly as you have outlined above. I have a number of .MAT files that were generated by a different program and I am trying to export the matrices (480×640 double) to individual ascii files. I am able to export a single file using
>save(‘NEW0470′,’-ASCII). But have been unsuccessful to run this in a batch command format. I am also trying to change the file extension to .txt, Below are 2 examples of the scripts I have been trying to run, it seems that the renaming process is working well, but every time I try to run it, I get a warning message telling me

“Warning: Attempt to write an unsupported data type to an ASCII file.
Variable ‘files’ not written to file.

Entire scrip:

files = dir('NEW*');
for k = 1:numel(files)
    input_name = files(k).name
    [path, name, extension] = fileparts(input_name)
    output_name = fullfile(path, [name '.txt'])
    save(files(k).name,'-ASCII')
end

Subset that I tried as well, just to run the export function:

files = dir('NEW*');
for k = 1:numel(files)
    save(files(k).name,'-ASCII')
end

Not sure if this makes any sens to you, but if you have a chance to take a look and let me know what you think, would be fantastic.

Best regards,
Ian

Ian—When you use save with just the output filename and the -ascii option, it tries to save ALL the variables in the current workspace to the file. That’s almost certainly not what you intended. Also, the code that you included in your comment shows no call to load, so I have no where your script is getting the data you are trying to save. But generally, you’ll need to call load to read into a variable, and then supply the variable name in the call to save. Check the documentation for both load and save.

Steve,

Your code is working almost perfectly, but, whenever I go to the folder where I am storing the images I cannot see them. The files are there, but the images are blank. I am using Windows Picture and Fax viewer to open them. I can’t figure out if there is something with the code or there is something wrong with the Windows Picture and Fax viewer. This is the code I am using:

close all
files = dir (‘D:\Users\Camilo\Matlab Programs\*.bmp’);

for k = 1:numel(files)

A = imread(files(k).name);
% A = im2double(A);

A2 = imcrop(A,[30 25 1152 928]);
A3 = imcrop (A2,[539 165 1152 928]);

[ypix,xpix] = size (A3);

xdim = 1.98;
ydim =(ypix/xpix)*xdim;
xstart = -1;
ystart =(892-904)*(xdim/xpix);
x = 1.006;

A3 = imagesc([xstart x],[ydim ystart], A3);

grid on;
axis image;
axis xy;
xlabel(‘Axial Distance, in’)
ylabel(‘Vertical Distance, in’)
colormap(gray);

imwrite(A3, [‘D:\Users\Camilo\Matlab Programs\Cropped\’files(k).name],’bmp’ )

end

Let me know what you think when you can. Thanks in advance.

Camilo

Steve !!!

I changed imwrite for saveas and it worked !!!

Thanks for showing us your code. It was very helpful.

Camilo

Camilo—The function imwrite takes a matrix of pixel values. In your first attempt, you were passing it the handle of a MATLAB graphics object, and imwrite interpreted that as a single-pixel image.

I am a beginner and I am trying to read some file names in a directory and save it in an array variable.
Can anyone help me?

Sree—The dir function returns a structure array containing the filenames and other information about the file.

s = dir('*.jpg');

You can combine the filenames into a single cell array using the comma-separated list syntax for structures:

names = {s.name};

Hi Steve

I am trying for batch processing using some satellite data whose names are as follows for example

ID2r1-AMSRE-D.252004150A.v03.10V
ID2r1-AMSRE-D.252004150A.v03.89V
ID2r1-AMSRE-D.252004150D.v03.10V
ID2r1-AMSRE-D.252004150D.v03.89V
ID2r1-AMSRE-D.252004151A.v03.89V

etc.

these are the examples of files. I am unable to process them in batch. Although I could read them individually and then save them in mat format. But it takes time and I want to do batch processing and the necessary computations. May I ask your help?

hi steve,

could you explain to me how i would be able to use the dir function, to do a loop through a directory and all of the subfolders in the directory for files that have the following format.

i have several subfolders in my directory. specifically ones that correspond to a date (ie. 20091011), and in each of those folders, there are several subfolders corresponding to a specific image set. In each of those folders are about 47 files, and I need to process the most recent/the last file in those folders

I00000XX (XX = is a series of numbers corresponding to the file name)…. there is no file extension. (its a DICOM file).

The subfolders are as follows:

ImageData (contains 1 folder) > MDX1 (contains one folder) > image (contains several folders, each corresponding to a date) > 20091002 (contains several folders, each corresponding to a image set) > E0000012 > all of the files, of which the last file is the file I need.

I want to create a list of sorts of all of these files (ie, path).

Then I want to run an executable on all of these files, to get an output that i can save in matrix form

thanks much!

Sana—It seems like a matter of methodical programming. I can think of several approaches. You can start by using dir to get a list of files inside ImageData/MDX1/image. You can then loop over the set returned by dir and building up a cell array containing names of things that are directories and whose names contain 8 decimal digits. Then you’ll need to loop over the subfolders, continuing to use dir. Use datenum on the modification date returned by dir in order to find the most recent file.

I can also imagine a recursive approach or an iterator approach, but I would only recommend those if you are familiar with those programming techniques.

Hi Steve,

I have a problem in Matlab which Doug Hull has been trying to help me with but maybe you will be better equipped as it is essentially an image processing problem.

I have a folder of 12 grayscale images all of 210 pixels high and 215 wide. I also have a blank canvas of white pixels which is 215 pixels high and 219 pixels wide. Each image must be placed on the blank canvas in a different way, the distances required between the left edge of the image and the left edge of the blank canvas is stored in a column vecotr called extra_white_pix_left and the distance required between between the top edge of the image and the top edge of the blank canvas is stored in a column vector called extra_white_pix_top. I have been able to carry out the task for one image with the following loop:

for a=1:210
for b=1:215
blank_test(a+1,b+3)=im_test(a,b);
end
end

where blank_test is the blank canvas, im_test is the original 210×215 image, 3 is the entry for extra_white_pix_left for this particular image and 1 is the entry for extra_white_pix_top for this particular image. So this image is spaced with one row of pixels of white above it and three columns of pixels of white to the left of it(because the white canvas is 215×219, there are four rows of white pixels below it and 1 row of white pixels to the right of it).

I need to be able to loop through the whole folder of images and carry this out. To do this I thought about using two loops, one to imread each image and store its matrix in a cell array and another, probably nested, to carry out the change to each image/element of the cell array. Although I understand this general idea I can’t seem to find the right code for either of these two loops.

Big ask I know but do you think you could help me out, or at least send me in the right direction?

Cheers,

Dan

Steve, just an after thought if you are willing to help me out. I think maybe this could be done another way through storing each image in a three dimensional matrix where there are 12 elements in the third dimension. I have tried to create a loop to imread each image in to such a matrix using the CAT function:

for i=1:numel(RCF_im_dir)
k(i)=imread(RCF_im_dir(i).name);
im_mat=cat(3, [k(1)]:[k(end)]);
end

where RCF_im_dir is contains inforation on the 12 images I need to process and im_mat was the matrix I hoped to produce. This didn’t work, i’m not sure why. But even if it had I’m unsure how I would treat the three dimensional matrix im_mat in order to edit each image in the way I need to.

Cheers,

Dan

Steve! I managed to figure it all out myself. Who’s ya daddy!? I’m ya daddy! Thank you for the help you no doubt would have given had I not found success in my own endeavours.

Dan

Yo Steve, I have another issue. I’m putting in the code:

for i=1:numel(index_im_final)
fileName=[‘cropped.’ num2str(i)];
imwrite(index_im_final{i},fileName,tiff);
end

and I keep getting the error message:

??? Error using ==> Tiff>Tiff.Tiff at 497
Not enough input arguments.

Error in ==> Tiff at 1
classdef Tiff < handle

You know what I’m doing wrong?

Cheers,

Dan

Dan—Yep. That third input argument to imwrite is supposed to be a string, but you didn’t put tiff inside quotes. Therefore MATLAB thinks you’re trying to call the Tiff class constructor.

imwrite(index_im_final{i},fileName,'tiff');

I am trying to read in a grayscale image w/ imread

>> imread('Me1.png');
??? Error using ==> imread at 361
File "Me1.png" does not exist.

However,

>> imread('dog.png');

works. Both files are in the same directory. If I give the full path to Me1.png, it works ‘C:\…’. I don’t want to give the full path each time. Why would dog.png work and Me1.png not work? dog.png came w/ a toolbox I installed, and Me1.png I added to the same directory. I’m assuming that’s the issue, somehow. But can’t figure it out. Any help greatly appreciated.

John—Sounds like it might be an issue with the toolbox path cache. Select File / Preferences / General and click on “Update Toolbox Path Cache.”

In general I recommend against mixing your files in the same folder with a product you obtained elsewhere. You risk accidentally losing your own files if you upgrade that product later.

Steve,

You da man! Thanks so much, worked like a charm. And I will heed your warning about mixing personal files w/ toolbox files.

Thank you!

John—Glad to hear it worked. If I could follow up on my own suggestion about locating your files … put your own work completely outside the MATLAB program folder. This has a number of benefits. Recent versions of Windows, for example, tend to assume that users are not going to be putting their own personal work in the “Program Files” area. And the default configuration of backup programs such as Mozy (my favorite) won’t look for your files there either.

Steve, I need help again, please…

I need to save a set of processed images with a different filename. Each image needs to have a filename according to a time ‘t’ at which the image was taken. The equation for time ‘t’ as a function of x is:

t(x) = 0.3824x – 0.3824, where x = image number.

In summary, I would like to save my images with filenames that look something like:

Image 1: x = 1, t = 0 , filename should be 0.bmp
Image 2: x = 2, t = 0.3824, filename should be 03824.bmp
Image 3: x = 3, t = 0.76479, filename should be 076479.bmp

Code deleted. -SE

Thanks in advance for your help and time.

Camilo

Camilo—You’ll probably need to define your problem better, because all those floating-point number displays are approximations. I don’t see any real justification for writing one image with a 4-significant-digit filename and writing out another with a 5-significant-digit filename. Anyway, once you get the desired behavior worked out well, you can use sprintf (and maybe multiplication by a power of ten) to turn a floating-point number into a filename string.

Hi Steve,

I’m trying to stack individual *.tif frames into movies, but the frames are in individual subfolders of the working directory, and the names of those subfolders changes from batch to batch.

So, for example:
In folder 2010-07-12 there are subfolders A, B, and C.
Folder A contains files Aa001.tif thru AaXXX.tif, B contains Bb001.tif thru BbXXX.tif, etc.
I’d like to have MATLAB stack the tifs to make the stacked file A.tif in folder A, B.tif in folder B, etc. (XXX is the frame number)

My thought was to create a text file containing the subfolder, current base file name for the frames, the new name the files will have when finished, and the number of frames within the subfolder (eventually I’d like to use dir to get the number of frames, but I’m not there yet). I thought of treating the text file as a cell array. The thing is, the number of folders will change, as well as their names. So going back to my example, folder 2010-07-13 might have subfolders A, C, Q, and R.

I’m fairly certain there is a simple way to do this, but I am new to MATLAB (and programming in general) and haven’t figured it out yet.

Here’s what I have at the moment: (The ‘0’ and ’00’ in the file names lets it find A001.tif in one folder and A01.tif in another, since the number of frames differs from movie to movie.)

stacksarray = load('stacklist.txt');
numstacks = size(stacksarray,1);
for r = 1:numstacks
    folder = stacksarray(r,1);
    filename = stacksarray(r,2);
    newfilename = stacksarray(r,3);
    length = stacksarray(r,4);
        for n=1:length
            if length < 100
                if n < 10
                A = imread(['.\' folder '\' filename '0' num2str(n) '.tif']);
                else
                A = imread(['.\' folder '\' filename num2str(n) '.tif']);
                end
            elseif length < 1000
                if n < 10
                A = imread(['.\' folder '\' filename '00' num2str(n) '.tif']);
                elseif n < 100
                A=imread(['.\' folder '\' filename '0' num2str(n) '.tif']);
                else
                A = imread(['.\' folder '\' filename num2str(n) '.tif']);
                end
            end
            imwrite(A,['.\' folder '\' newfilename '.tif'],'Writemode','append','Compression','none');
        end
end

Could you help me out? I’d really appreciate it.
Thanks,
Beth

Beth—I might start with something like this:

subfolders = dir('2010-07-12');
for k = 1:numel(subfolders)
  if subfolders(k).isdir && ...
     ~strcmp(subfolders(k).name), '.') && ...
     ~strcmp(subfolders(k).name), '..')
    tiffiles = dir(fullfile('2007-07-12', ...
        subfolders(k).name, '*.tif'));
    for q = 1:numel(tiffiles)
      f = imread(tiffiles(q).name);
      do_something_with_image_q
    end
  end
end
     

Steve,

I am trying to develop a code that will take a batch of images from a folder and convert them from HDF5 format to tif format. I have successfully developed code that will do one image at a time but I would like to create code that will do the entire folder. When I run the program, the second for loop seems to not update… Any advice on getting that second loop to update?

Code:

[MyFileIn,PathIn] = uigetfile(‘*.h5′);
MyFileIn = fullfile(PathIn,MyFileIn);

for k = 1:numel(PathIn)
files = dir(fullfile(PathIn, ‘*.h5′));
end

%% PATHSTR/NAME/MYFILEIN/ SOMETHING IN UIPUTFILE NEEDS TO BE UPDATED TO
%% GET THE LOOP WORKING CORRECTLY. 7/12/2010

% files = dir(fullfile(PathIn, ‘*.h5′));
for a = 1:numel(files);
info = hdf5info(MyFileIn);
Data = info.GroupHierarchy.Groups(1).Groups(3).Datasets(1).Name;

image1 = hdf5read(MyFileIn,Data);
image1 = rot90(image1, -1);
image1 = fliplr(image1);
[pathstr, name, ext, versn] = fileparts(MyFileIn);
[MyFileOut,PathOut] = uiputfile(fullfile(pathstr,name));
% MyFileOut = fullfile(PathOut,MyFileOut)

t = Tiff(MyFileOut,’w’);
% setup file format
tagstruct.ImageLength = size(image1,1);
tagstruct.ImageWidth = size(image1,2);
tagstruct.Photometric = Tiff.Photometric.MinIsBlack;
tagstruct.BitsPerSample = 16;
tagstruct.SamplesPerPixel = 1;
tagstruct.RowsPerStrip = 16;
tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky;
tagstruct.Software = ‘MATLAB';
t.setTag(tagstruct);
% save file
t.write(image1);
t.close();

end

Hi Steve,

I have a bunch of files in the DICOM format in a folder. As Sana mentioned, they often do not have an extension. I use dir(‘*’), but instead of 367 files, it gives me 370 files, an additional ‘.’, ‘..’ & ‘folder’ file. How do I get only the files in the dicom format?

Thanks.
Haseeb

Haseeb—Try something like this:

s = dir('*');
for k = 1:numel(s)
    if ~s(k).isdir && isdicom(s(k).name)
       % do something useful
    end
end

Hi Steve – many thanks for your very helopful information above. I am something of a “newbie” to Matlab and was wondering if you could answer my question below:

I have around 200 DAT files which are populated with experimental data from some tests I have been running. For each file:

column 1 = time
column 2 = Output from Wave Gauge 1
column 3 = Pressure

I have written some bits of code that work out the velocity from the wave gauge 1 output, then multiply this by pressure and a seperately defined “Area” parameter, giving me a power output.

I want to batch process to avoid having to do this by hand. At the moment, I have been reading in individual columns using code such as:

time=MT045006(:,1)
where MT45006 is the name of one of my files.

How can I get Matlab to do this for all of my files, which all have different names?

Apologies for this schoolboy question – as I say I am jkust learning!

Regards,

Euan

Euan—This post was intended to answer this sort of question. Can you say more about what additional information you’re looking for?

Hi Steve,

I’m trying to process a bunch of images in a folder using this code:

files = dir('C:\Users\Ricardo\Desktop\TESTE_BULK\*.jpg');
for k = 1:numel(files)
   I = imread(files(k).name);
   H = medfilt2(I);
   J = histeq(H);
   level = graythresh(J);
   BW = im2bw(J,level);
   imwrite(BW, ['binario\' files(k).name]);
end

But I get an error:
“??? Error using ==> imread at 374
File “Galega_Vulgar_01.jpg” does not exist.”

That file is the first one in the folder “TESTE_BULK”.

Can you please tell me what am I doing wrong?
Thanks in advance.

Best regards
Ricardo

Ricardo—files(k).name contains just the base filename; it doesn’t include the directory name. That’s why imread can’t find the image. Try this instead:

I = imread(fullfile('C:\Users\Ricardo\Desktop\TESTE_BULK', ...
    files(k).name));

Steve, kindly help fix this code. Having used roipoly, i want to save the crop part as RGBCROP and with the files(k).name. That is assume k=1
then the files(k).name=001_1.jpg
How do i write the command to save RegOfInt for k=i as RGBCROP001_1
files = dir(‘*.JPG’);
for k = 1:numel(files);
MyImage = imread(files(k).name);
MyImage = im2double(MyImage);
MyImage = imresize(MyImage, [640 480]);
RegOfInt= roipoly(MyImage);
save([‘RGBCROP/files(k).name’] ,’RegOfInt’);

end
it saving as “RGBCROP/files(k).name” which is wrong cos it wont change numbers when image changes.

Osunmbs—Sadly, MATLAB is doing what you said instead of what you meant. You told MATLAB to save to a file named RGBCROP/files(k).name, so that’s what it did.

Try this instead:

save(['RGBCROP/' files(k).name], 'RegOfInt');

Or:

save(sprintf('RGBCROP/%s', files(k).name), 'RegOfInt');

i have used your code. i am processing medical images.my folder has 89 JPEG images, but these are like IM-0001-0099 i.e there is no extension. when i use

it returns nothing. could you please help me to find the solution of my problem
thanx

Hi steve,thanks for your example above.

Im trying to get specific information from Dicom file .The problem is,i can easily read single file information using
the code below,but i have to read about 100 dicom file and store the information in excell file.

As additional to my problem,do you have any idea how i can save the summary of information obtain from the 100 files to an xls file.Thanks in advance


metadata = dicominfo(filename);
imageorientation = metadata.(dicomlookup('0020','0037'));

.

Hai Steve,somehow i can run and obtain the specific tag of the Dicom files using the algo below .I successfully get the tag when I used the Dicom image from the ‘brain image ‘ provided by matlab.I noticed the file is save as ‘DCM’ type. But,the problem is.for my mammogram images,it is a Dicom,but for some reason i dont know why it is save as ‘file’ type.Thus,i fail to run my algo below.Do you know which part of my algo i need to modify.Furthermore, i still cannot find how to safe the information into xls format. Thank in advance.


files=dir('*.DCM');
>> for k=1:numel(files)
metadata=dicominfo(files(k) .name);
a=metadata, (dicomlookup('0008','0060'));
ans=a
end

Rodney—I’m afraid that I have no idea how your DICOM files were created or why they contain the metadata they do. As for creating Excel files, I recommend that you take a look at the xlswrite function.

hai steve,i think i got the solution.basically this is what u taught to Haseeb.Thanks steve

image=dir(‘*’);
for k=1:numel(image)
if ~image(k) .isdir && isdicom(image(k) .name) % i think here is the problem,as it dont have the right extension
metadata=dicominfo (image(k) .name);
ans=metadata
end
end

Hi there: I’m trying to write a script that will take all jpg files from a folder specified by the user and rotate them by -90 degrees before putting them ideally in a new folder also specified by the user. My code looks like this:

d = uigetdir(‘/Users/myname/Documents/MATLAB’, ‘Pick the directory to get .jpg files’); %Get input directory
files = dir(fullfile(d,’*.jpg’)); % Only take .jpg files
for k = 1:numel(files); % For all of the elements in the specified directory
rotatedpics = imread(files(k).name);% read the pictures in
rotatedpics = imrotate(files, -90); % rotate the pictures
imwrite(rotatedpics, [‘rotated/’ files(k).name]); %and write the pictures into another specified director
end

As soon as I try to run I get an error that my file “1.jpg” does not exist!

Any help would be appreciated; I’m a complete MATLAB novice :)

Hi Steve,
i am trying to process some images by following the MATLAB demo. after getting the names of files when i try to see any of the files then its gives the error. the detail is asfollows:

>> fileFolder = fullfile(matlabroot,'work','original');
dirOutput = dir(fullfile(fileFolder,'AT3_1m4_*.jpg'));
>> fileNames = {dirOutput.name}'

fileNames = 

    'AT3_1m4_001.jpg'
    'AT3_1m4_002.jpg'
    'AT3_1m4_003.jpg'
    'AT3_1m4_004.jpg'
    'AT3_1m4_005.jpg'
    'AT3_1m4_006.jpg'
    'AT3_1m4_007.jpg'

    [...]

    'AT3_1m4_116.jpg'
    'AT3_1m4_117.jpg'
    'AT3_1m4_118.jpg'
    'AT3_1m4_119.jpg'
    'AT3_1m4_120.jpg'

>> I=imread(fileNames{1});
??? Error using ==> imread
File "AT3_1m4_001.jpg" does not exist.

I could not understand where is the problem? please help me to solve this.

Thanks a lot

Hai Steve, please help me to fix this code.I am trying to read the DICOM files stored in the folder “F:/DICOMs/Subject1″ using this code.

function displaydir(path1)
path1=’F:\DICOMs\Subject1\*.dcm';
nooffiles=numel(path1);
for k=1:nooffiles
path1(k).name; I=dicomread(fullfile(‘F:\DICOMs\Subject1′),path1(k).name);
imshow(I,[]);
pause;
end

But, i am getting the error,

??? Improper index matrix reference.

Error in ==> displaydir at 10
path1(k).name;

Please help me to solve this problem…..Thanks in advance Steve…..

I know this is not MATLAB way, but if you are in Linux/Mac, then with ImageMagick package this is as simple as:

ls *.jpg | convert -resize 640×480

or if you want to leverage all your 4 cores:

find . -name *.jpg | xargs convert -resize 640×480

Hi Steve,

I was wondering if you please make a suggestion for a couple of tweaks for the initial posting of the code you have here:

1) Output the file name for each file that was processed to an external source such as a spreadsheet. (I’m trying to generate some sort of a tracking method for the batches of images that are being processed.)

2) Generate a measurement for each corresponding file entry (say, something like area, from regionprops), to be output to the same spreadsheet.

Thank you very much and have a good one.

Cheers

These postings are the author's and don't necessarily represent the opinions of MathWorks.