Home > Enterprise >  Variable as argument for imread in Matlab?
Variable as argument for imread in Matlab?

Time:11-20

I am trying to run an image analysis script on ~5,000 files in Matlab. I'm trying to run the main part of the script inside a for loop and iterate across every file name. I've listed the directory as a a variable and have come up with something like the following:

images = dir
images.name
imagesdim = size(images)
imageslength = imagesdim(1)

for i = 1:imageslength
    cimg =  imread(images(i,1).name);
    etc etc
end

However, this doesn't seem to be an acceptable input argument for imread. Is there any way I can format this list so that I can use a variable here, or will I have to copy this argument 5,000 times?

CodePudding user response:

I do this in directories of images using the function form of the dir command. For example, if you are working with TIFF files:

dir_items = dir('*.tiff');
file_names = {dir_items.name};
disp('Using .tiff files found in current directory:')
disp(file_names');
for k = 1:length(file_names)
    disp(file_names{k})
    cimg = imread(file_names{k});
end

If you can't use the wildcard filter like "*.tiff", then you have to check the isdir field of each struct in the array, like so:

dir_items = dir;
for k = 1:length(dir_items)
    if dir_items(k).isdir==1
        fprintf(1,'%s is a directory (ignore)\n',dir_items(k).name)
    else
        disp(dir_items(k).name)
        cimg = imread(dir_items(k).name)
    end
end

CodePudding user response:

A much easier way of iterating through a folder, or nested folder of images in MATLAB is to use imageDatastore.

imds = imageDatastore(desiredDirectory,"FileExtensions",[".tif",".tiff"]);

while hasdata(imds)
     img = read(imds);
     % Your code that operates on img
end
  • Related