0

I am beginner in MATLAB. I would like to load 200 image files (size 192x192) in a specific folder by using a for loop.

The image names are '1.png', '2.png', '3.png' and so on.

My code is as below.

list = dir('C:/preds/*.png');
N = size(list,1);
sum_image = zeros(192,192,200);
for i = 1:N
    sum_image(:,:,i) = imread('C:/preds/i.png');
end

Which part should I change ?

1
  • Is anything in particular not working? Getting errors anywhere, etc. Also, are the filenames 0 padded... so 001, 002 ... 009, 010...etc. or 1, 2, ..,9,10 Commented Nov 9, 2017 at 17:47

3 Answers 3

1

I would probably do it like the code below: You are currently getting the list of filenames then not really doing much with it. Iterating over the list is safer otherwise if there is a missing number you could have issues. Also, the sort maybe unnecessary depending if you image numbering is zero-padded so they come out in the correct order ... but better safe than sorry. One other small change initializing the array to size N instead of hard-coding 200. This will make it more flexible.

searchDir = 'C:\preds\';
list = dir([searchDir '*.png']);
nameList = {list.name}; %Get array of names
imNum = str2double(strrep(nameList,'.png','')); %Get image number
[~,idx] = sort(imNum); %sort it 
nameList = nameList(idx);

N = numel(nameList);
sum_image = zeros(192,192,N);
for i=1:N
    sum_image(:,:,i) = imread(fullfile(searchDir,nameList{i}));
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your comments!
No problem & no need for thanks. Just upvote if useful and downvote if not.
0

I would suggest changing the line within the loop to the following:

sum_image(:,:,i) = imread(['C:/preds/', num2str(i), '.png']);

MATLAB treats the i in your string as a character and not the variable i. The above line of code builds your string piece by piece.

1 Comment

Thank you for your comments
0

If this isn't a homework problem, the right answer to this question is don't write this as a for loop. Use an imageDatastore:

https://www.mathworks.com/help/matlab/ref/imagedatastore.html

ds = imageDatastore('C:/preds/');
sumImageCellArray = readall(ds);
sumImage = cat(3,sumImageCellArray{:});

1 Comment

Thank you for your comments!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.