Selecting n random elements within a for loop

Hi everyone,
So assume I have a dataset with 10 folders (each folder corresponding to a category).
In my example :
ListOfAllCategories is a 1x10 cell containing the list of all categories
ImageListForEachCategory is a 10x1 map that returns all images belonging to a given category.
My goal is to (1) "extract" all images belonging to all 10 categories and (2) draw n random images from the whole pool (all categories combined). However, I am encountering problems at the very beginning of the code. I am doing the following (to begin with) :
for i=1:length(ListOfAllCategories)
A = ListOfAllCategories{i};
B = ImageListForEachCategory(A);
disp(B)
end
When I display "B", I get a list of all the images from all categories but the folder in the workspace contains only the images belonging to the first category. Should I use a second For Loop in that case? Also, is there a different way to directly draw n images from the whole pool?
Thank you very much.
Best regards.

 채택된 답변

Image Analyst
Image Analyst 2020년 9월 14일

0 개 추천

Have you seen dir() with two **?
% Get a list of all PNG files in all subfolders of topLevelFolder.
allFiles = dir([topLevelFolder, '**/*.png']); % All files in all 10 subfolders.
% Get only a subset of n of them:
randomIndexes = randperm(length(allFiles), n);
subset = allFiles(randomIndexes)

댓글 수: 7

M J
M J 2020년 9월 17일
편집: M J 2020년 9월 17일
Thank you very much for the response! My only problem is that the "images" I was talking about here are subfolders containing multiple png files (i.e. these are patches cropped out of each image). Is there a way I can get a list of all of these "bottom" subfolders (aka images) along with their paths, and work at the image level?
I don't know if that was clear. If not, I apologize in advance.
Thank you!
I don't know why the code I gave you does not work. It will give you the filenames of all those files. Isn't that what you want???
M J
M J 2020년 9월 17일
Silly mistake on my end. The png files were named with digits (right before the ".png") so I changed them and it ended up working. Billions and billions of thanks !!
It shouldn't matter whether the characters are letters or numerical digits - they're all the same as far as dir() is concerned.
M J
M J 2020년 9월 18일
편집: M J 2020년 9월 18일
Sorry to bother again, but another question that follows : Is there a way to list all subfolders that fall exactly 2 levels below the top level folder?
Yes, you can call my attached function twice to get the grandparent of a folder. If it's the same as the top level folder, it's exactly 2 levels deep.
M J
M J 2020년 9월 19일
Thank you so much !

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

M J
2020년 9월 14일

댓글:

M J
2020년 9월 19일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by