5
votes

I have a problem reading multiple images in Matlab from a folder. I want to read with their original name (with the command imread because are multiband). The names of the images are like '2001_01', '2001_02'. This is my code:

myPath= 'C:\images\'; %'
a=dir(fullfile(myPath,'*.tif'));
fileNames={a.name};

And then...

for k = 1:length(fileNames)
    filename = [fileNames(k).name];  
    I = imread(filename);
end

But it doesn't work and I don't know how to save and imread each one individually. Does somebody know how can I do it? Really thanks in advance,

3
Does it return the full file path? - user349026

3 Answers

6
votes
  1. Regarding the first problem:

    But it doesn't work...

    Just assign the output of dir directly into fileNames (without brackets):

    fileNames = dir(fullfile(myPath, '*.tif'));
    
  2. Regarding the second problem:

    ... I don't know how to save and imread each one individually.

    it seems that you need a cell array to store all images in a single collection. First, define the cell array to have the right size:

    C = cell(length(fileNames), 1);
    

    and then store each image into a different cell:

    for k = 1:length(fileNames)
        filename = fileNames(k).name;
        C{k} = imread(filename);
    end
    

    To access any image in the cell array C later, use curly braces ({}). For instance, the second image is accessed as follows: C{2}.

2
votes

Instead of

 fileNames={a.name};

Try

fileNames = arrayfun( @(x) fullfile( myPath, x.name ), a, 'UniformOutput', false );

Then, in the loop you can access the k-th file name as

I = imread( filenames{k} );
1
votes

Does it return the full file path? fileNames(k).name ? or just the actual file name? You might need to append myPath with filename taking care of slashes as well

fileName = strcat(myPath, fileName)

Then do the imread, make sure you have looked at the slashes once contactenated