How to extract random subset of images from a cell array?
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Allison Lepp
am 16 Feb. 2022
Kommentiert: Allison Lepp
am 16 Feb. 2022
Hi all,
I'm working on a code that imports all images in a given file and stores them in a cell array. I wish to extract a random subset (n=100) of those images and save them in a separate cell array. Functions like 'randperm' aren't compatible with cell arrays, and I've not been able to find a similar function that is.
Any suggestions?
Alternatively, a similar solution that imports a random 100 images from the folder and saves a step, is also welcome. Here is the base code (though it may not be necessary):
cd '/Users/Documents/MATLAB/Grain Shape/60-62.fld' % modify this to change directory (cd) to appropriate folder
images = dir('*.png'); % loading all .png files in the directory
% read, convert to greyscale, and save raw images
for i = 1:440 % adjust maximum number for number of images imported
im_{i} = imread(images(i).name);
im_{i} = rgb2gray(im_{i});
end
0 Kommentare
Akzeptierte Antwort
Jan
am 16 Feb. 2022
Bearbeitet: Jan
am 16 Feb. 2022
Of course randperm works with cell arrays:
random_subset = im_(randperm(numel(im_), 100));
This selects 100 elements in random order without repetitions.
A hint: Do not change the current directory. Each callback of a GUI or a timer could do this unexpectedly also. Use absolute path names instead:
folder = '/Users/Documents/MATLAB/Grain Shape/60-62.fld';
images = dir(fullfile(folder, '*.png'));
for i = 1:numel(images)
im_{i} = imread(fullfile(folder, images(i).name));
im_{i} = rgb2gray(im_{i});
end
And if you do not want to import all images, but only the random subset:
folder = '/Users/Documents/MATLAB/Grain Shape/60-62.fld';
images = dir(fullfile(folder, '*.png'));
images = images(randperm(numel(images), 100));
... as above
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Entering Commands finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!