How to sort the struct array after reading number of images using dir command

Hi,
I am reading images thru 'dir' command from a folder but those are unsorted , I am expecting them as sorted....
file2=dir(file); // file contains path to the folder where I stored the images
for k = 1 : numel(file2)
im = imread(file2(k).name);
folder1=sprintf('%s%s%s%d',targetfolder,index,fi,j);
imwrite(im,[folder1,'.jpg']);
j=j+1;
end

5 Comments

Mohammad Bhat's "Answer" moved here:
Sir, I tried it due to a usage of recursion in a function my system shows out of memory and halts despite having 8GB ram.
I have 106 images like attached image....my system gets stuck ...while using it
@Mohammad Bhat: perhaps your code is recursive. But unless you show use that code we have no idea what you are doing. And if you don't show us any warning or error message then we have no idea why your code failed.
If you want help then you have to show us the code that you used, and the complete error message. This means all of the red text.
PS: Please do not use answers for comments. The comments are for commenting.
Mohammad Bhat's "Answer" moved here:
source_file1= 'C:\Users\Hp\Desktop\New folder\';
targetfolder='C:\Users\Hp\Desktop\target\';
extn='*.jpg';
fg='\';
h=; % Total number of subfolders in main folder
% index tokeep track sub folders in main folder
index=num2str(h);
file = sprintf('%s%s%s%s',source_file1,index,fg,extn); % Whole images in current sub-folder
file1=sprintf('%s%s%s',source_file1,index,fg); % current Sub Folder tracking
file2=dir(file);
for k = 1 : numel(file2) % To keep track for all images in each sub-folder
im = imread(file2(k).name);
folder1=sprintf('%s%s%s%d',targetfolder,index,fi,j);
imwrite(im,[folder1,'.jpg']);
j=j+1;
end
Mohammad Bhat's "Answer" moved here:
D='C:\Users\Hp\Desktop\3';
% where I have stored '.jpg' images 106 in number
S = dir(fullfile(D,'*.jpg'));
N = natsortfiles({S.name});
Error using natsortfiles (line 15)
endfirst input supplied is not a struct.
@Mohammad Bhat: that is an unusual error. Line 15 of natsortfiles (that I wrote) is a comment, with no executable code anywhere near it. Nowhere in any of the Mfiles of that FEX submission is there anything called endfirst. An internet search did not locate anything related to the term "endfirst".
Are you sure that you downloaded the function from the link that I gave you?
I wonder if this is an undocumented beta-feature: what MATLAB version are you using?

Sign in to comment.

 Accepted Answer

"I am reading images thru 'dir' command from a folder but those are unsorted , I am expecting them as sorted...."
The order of the output of dir is determined by the OS and is not specified.
You can sort filenames very easily by using my FEX submission natsortfiles, which provides an alphanumeric sort for filenames (i.e. so that any numbers in the filenames are sorted into numeric order). You will need to download it, unzip it, and place the Mfiles on the MATLAB Search Path (e.g. in the current directory):
It is easy to use, and there are example in the Mfile and HTML documentation. Here is a basic working example:
D = 'C:\Test';
S = dir(fullfile(D,'*.txt'));
S = natsortfiles(S); % alphanumeric sort by filename
for k = 1:numel(N)
filename = fullfile(D,S(k).name)
...
end

17 Comments

Sir , I am not getting names as sorted , I included a struct fields
Sir, here is proof (function [X,ndx] = natsortfiles(X,varargin) % Alphanumeric / Natural-Order sort of a cell array of filenames/filepaths. % % (c) 2017 Stephen Cobeldick % % Alphanumeric sort of a cell array of filenames or filepaths: sorts by % character order and also by the values of any numbers that are within % the strings. Filenames, file-extensions, and directories (if supplied))........
please see the text document for steps as well as errors..
If i am using extension .jpg instead of .txt my system is getting hanged...
see the error Sir
>> D='C:\Users\Hp\Desktop\3';
>> S=dir(fullfile(D,'*.jpg'));
>> N = natsortfiles({S.name});
41 ind = find(file == '/'|file == '\', 1, 'last');
With this directory
it works for me:
>> S = dir('*.jpg');
>> N = natsortfiles({S.name});
>> N{:}
ans = 1.jpg
ans = 10.jpg
ans = 11.jpg
ans = 12.jpg
ans = 13.jpg
ans = 100.jpg
ans = 101.jpg
ans = 102.jpg
ans = 103.jpg
ans = 104.jpg
ans = 105.jpg
Please run these commands:
D = 'C:\Users\Hp\Desktop\3';
S = dir(fullfile(D,'*.jpg'));
save('test.mat','S')
and then upload the .mat file by clicking the paperclip button.
ans = 1.jpg ans = 10.jpg ans = 11.jpg ans = 12.jpg ans = 13.jpg ans = 100.jpg ans = 101.jpg ans = 102.jpg ans = 103.jpg ans = 104.jpg ans = 105.jpg The names of files are not sorted, 1.jpg follows 10.jpg and so on evident from your reply, I just want to 1.jpg,2.jpg,.......
Actually that was the output of initial 'dir' command, your code did nothing than, I just want them in order as afar as there name is concern just like 1.jpg,2.jpg,........
I loaded your filenames and natsortfiles worked perfectly for me:
>> load test.mat
>> N = natsortfiles({S.name});
>> N{:}
ans = 1.jpg
ans = 2.jpg
ans = 3.jpg
ans = 4.jpg
ans = 5.jpg
ans = 6.jpg
ans = 7.jpg
ans = 8.jpg
ans = 9.jpg
ans = 10.jpg
ans = 11.jpg
ans = 12.jpg
ans = 13.jpg
ans = 14.jpg
ans = 15.jpg
ans = 16.jpg
ans = 17.jpg
ans = 18.jpg
ans = 19.jpg
ans = 20.jpg
ans = 21.jpg
...
ans = 98.jpg
ans = 99.jpg
ans = 100.jpg
ans = 101.jpg
ans = 102.jpg
ans = 103.jpg
ans = 104.jpg
ans = 105.jpg
ans = 106.jpg
>>
Note that natsortfiles does NOT accept the structure that is output from dir. As all of the examples show and its documentation clearly explains, it requires a cell array of file names. All of the examples show how to get this from the structure.
Sir, please give me steps , how should I get desired output in my case,
@Mohammad Bhat: please run these commands and upload the .mat file in a new comment:
D = 'C:\Users\Hp\Desktop\3';
S = dir(fullfile(D,'*.jpg'));
C = {S.name};
N = natsortfiles(C);
save('test.mat','S','C','N')
Also show the output of this command (in the same comment please):
which natsortfiles -all
Sir I followed above steps I got following errors:-
Out of memory. The likely cause is an infinite recursion within the program.
Error in natsort (line 126)
[pth,nam,ext] = cellfun(@fileparts,X(:),'UniformOutput',false);
The Output of above command which you have asked is :- C:\Users\Hp\Desktop\lowner\natsortfiles.m
If you provide me your e-mail , I can send my files to you...
@Mohammad Bhat: please put both the code that you are running, natsortfiles and natsort files into a zip file and upload them into a new comment (not an answer).
Most importantly: please show the outputs to these commands:
which fileparts -all
which cellfun -all
Have you named any variable, function, or mfile fileparts ?

Sign in to comment.

More Answers (1)

After following these steps, It worked for another function
https://in.mathworks.com/matlabcentral/fileexchange/10959-sort-nat--natural-order-sort
D = 'C:\Users\Hp\Desktop\3';
S = dir(fullfile(D,'*.jpg'));
C = {S.name};
[cs,index] = sort_nat(C);
cs
I am attaching '.mat' file after saving result

10 Comments

Sir , I have not modified any code in these two files....
I noticed you've accepted an answer. So is this question solved, or not? In your "Answer" here, I do not see any question or anything for us to do, just an announcment.
Sir, it partly solved my problem, after following some steps, the fucntion 'natsortfiles' went to infinite loop, instead this 'natsortfiles'function sort_nat(); fucntion solved my problem. I have informed it to the @Stephen Cobeldick as well. Since , after that he told me to follow some steps that is why I commented furthur, may be these things will be helpful for another person or @Stephen as well...any way thank you Sir Stephen .
@Mohammad Bhat: if you are happy to help me I would like to find out why you are getting an infinite loop. This is the first time that anyone has reported this behavior using natsortfiles, and I would appreciate your help in discovering why this happens!
The output of which fileparts -all is :-
C:\Program Files\MATLAB\R2016a\toolbox\matlab\iofun\fileparts.m
The Output of which cellfun -all is :-
C:\Program Files\MATLAB\R2016a\toolbox\distcomp\parallel\@codistributed\cellfun.m % codistributed method
I once again checked
D = 'C:\Users\Hp\Desktop\3';
S = dir(fullfile(D,'*.jpg'));
C = {S.name};
[cs,index] = sort_nat(C);
[~,idx] = natsortfiles({S.name});
Out of memory. The likely cause is an infinite recursion within the program.
Error in natsort (line 134) [~,ndx] = natsort(ext,varargin{:});
@Mohammad Bhat: can you please upload these three files in a new comment:
  1. natsortfiles.
  2. natsort.
  3. the file where natsortfiles is called.
It is interesting that the errors that you have shown show a different line each time. I checked the versions available online and neither of them make any kind of recursive calls.
sir, here I attached all the necessary files which you have asked
@Mohammad Bhat: thank you for uploading the files.
The problem is very simple: you put the wrong function into the file natsort.m. If you have a look at natsort you will see that you have actually copied the function natsortfiles into this file. This explains why you are getting recursive calls, because what you thought was natsort was just a copy of natsortfiles, and so you accidentally forced natsortfiles to call itself recursively.
I just checked the online versions and the functions are correctly named (matching the filenames), so you must have made this mistake when copying the functions somehow.
I recommend that you simply download the correct natsort.m and natsortfiles.m from the link in my answer, by clicking the big blue "Download" button at the top.
Thank you for your patience and assistance in providing the files and information that I requested. I am very glad to have figured out why it did not work!
Bingo, yes I checked now, I was doing a mistake, you guessed it correctly, thanks a lot.

Sign in to comment.

Categories

Asked:

on 21 Feb 2018

Edited:

on 18 Apr 2021

Community Treasure Hunt

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

Start Hunting!