How to read and work with all the files from a directory ?

I have a directory full of image-files. I want to read all the files and then calculate the number of white pixel present for each of the files then write to to another file. To achieve this I used following code but in vein.
mydir = 'E:\matlab\dog\';
allentries = dir(mydir);
diridxs = [allentries.isdir];
alldirs = allentries(diridxs);
allfiles = allentries(~diridxs);
for ctr = 1:length(allfiles)
disp(nnz(edge(rgb2gray(imread(allfiles(ctr).name)))));
end
After using this code matlab is showing some error [File "247000.jpg" does not exist]. Though that file exists in that path. How to get rid of that problem?

 Accepted Answer

fullfile(mydir, allfiles(ctr).name)

3 Comments

I have used that code and it works perfectly but the problem is that each time I use the number of white pixel count (using nnz() function) it only shows it sequentially. I have used the escape sequence to make new line ('\n') but in the output file does not seem to process the '\n'. How to deal with that?
My code so far::
mydir = 'E:\matlab\dog\';
fid=fopen('E:\matlab\all data.txt','w');
allentries = dir(mydir); % array of all files and dirs within target
diridxs = [allentries.isdir];
alldirs = allentries(diridxs); % array of all the dirs
allfiles = allentries(~diridxs); % array of all the files
for ctr = 1:length(allfiles)
x = fullfile(mydir, allfiles(ctr).name);
%disp(x);
pix = nnz(edge(rgb2gray(imread(x))));
fprintf(fid,'%d\n',pix); // *""\n - not working""*
end
output::
123124125126127
where desired output is::
123
124
125
126
127
In your fopen() statement, change the 'w' to 'wt'

Sign in to comment.

More Answers (0)

Categories

Find more on App Building in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!