简体   繁体   中英

Variable as argument for imread in Matlab?

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 aa 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM