code to select one image each from multiple directory in matlab

To select one image each from multiple directories in MATLAB, you can use the following code snippet:

main.m
% set the directory paths
dir1 = 'path/to/dir1';
dir2 = 'path/to/dir2';
dir3 = 'path/to/dir3';

% create a cell array containing the directory paths
dirs = {dir1, dir2, dir3};

% set the file extension type
file_ext = '*.png';

% loop through each directory path
for d=1:length(dirs)
    % get a list of all files with the specified file extension
    file_list = dir(fullfile(dirs{d}, file_ext));
    
    % randomly select one file from the list
    file_index = randi(numel(file_list));
    selected_file = file_list(file_index).name;
    
    % read the selected image
    image = imread(fullfile(dirs{d}, selected_file));
    
    % do some processing with the image here
    
end
686 chars
27 lines

This code first sets the directory paths for the directories you want to select images from. These are stored in a cell array for easy iteration. The code then sets the file extension type (in this case it is *.png, but you can modify it to your needs).

A loop is then used to iterate through each directory path in dirs. Inside the loop, the code uses the dir function to get a list of all files in the current directory path that have the specified file extension. The randi function is then used to randomly select one file from the list, and the selected file's name is stored in selected_file.

Finally, the code uses the imread function to read the selected image file into a matrix. You can then do any processing you need with the image inside the loop.

gistlibby LogSnag