user2654568
user2654568

Reputation: 47

MATLAB Reading several images from folder

I have a folder called BasePics within a folder called Images. Inside BasePics there are 30 JPEG images. I'm wondering if the following is possible: Can a script be written that reads all of these images using the imread() command. The names of the images are somewhat sequential: C1A_Base.jpg, C1B_Base.jpg, C1C_Base.jpg, C2A_Base.jpg, C2B_Base.jpg, C2C_Base.jpg, etc.... all the way up to C10C_Base.jpg

Can a loop be used somehow:

    file = dir('Images\BasePics');
    NF = length(file);
    for k = 1:NF
        images(k) = imread(fullfile('ImagesBasePics',file(k))
        imagesc(images(k))
    end

This is a rough idea of what I want to do, but I'm wondering if it can be done with the current naming format I have in the Images folder. I would also like to have each image being read be its own variable with the same or similar name as it is named in the folder Images\BasePics currently, rather than have an concatenated array of 30 images all under the one variable images. I would like to have 30 separate variables, with names such as A1, A2,A3,B1,B2,B3 etc...

Also when I just ask for:

    dir images\BasePics

Matlab outputs 33 files, instead of 30. There are two extra files at the beginning of the folder: '.' and '..' and one at the end: 'Thumbs.db' These do not exist when I look at the folder separately, is there a way to programically have Matlab skip over these?

Thanks!!

Upvotes: 1

Views: 3169

Answers (2)

Peter
Peter

Reputation: 14927

You are very close. I would just use dir('Images\BasePics\*.jpg') to get rid of the extraneous files.

The naming system you want will not lend itself to additional batch processing (do you really want to type all of A1, A2, etc?). I would either keep it sequential, and store a list of the filenames to match, or use a struct array, like images.C1A, etc.

dirlist = dir('Images\BasePics\*.jpg');

for k = 1:length(dirlist);
    fname = dirlist(k).name;
    [path,name,ext] = fileparts(fname); % separate out base name of file
    images.(name) = imread(fullfile('Images\BasePics', fname));
end

Upvotes: 1

Shai
Shai

Reputation: 114786

Since you know the names of the files in advance, you can skip the dir and go ahead and read the files:

for l = 'ABC'
    for n=1:10
        nm = sprintf('C%d%c_Base.jpg', n, l );
        fnm = sprintf('%c%d', l, n );
        imgs.(fnm) = imread( fullfile('images','BasePics', nm ) );
    end
end

Now you have a struct imgs with fields A1...C10 for each image.

Upvotes: 2

Related Questions