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?

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 31 Mär. 2013
fullfile(mydir, allfiles(ctr).name)

3 Kommentare

Sayak
Sayak am 1 Apr. 2013
Bearbeitet: Walter Roberson am 1 Apr. 2013
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'
Ok, done. Thanks.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu App Building finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by