MATLAB: How to sort the files obtained by ImageDatastore

alphanumericComputer Vision Toolboxdatastoreimage processingimagedatastoreMATLABnatsortnatsortfilesnatural order sortsortnat

I used imageDatastore to obtain the directory of all the images in a folder.
Images = 'D:\Google Drive\MARYLAND\ENPM808 Independent Study\Independent Study\3D_map_poses\rgb';
rgb_image = imageDatastore(fullfile(Images),'IncludeSubfolders',false,'FileExtensions','.png','LabelSource','none');
But I realized that the order of the directories is not the same as the File Explorer and hence the generated video after processing the frames is erroneous.
Instead I need this to be in increasing order, (e.g. 1,3,7,9,10,16,…).
How can I do this? Thanks!

Best Answer

I don't know if it is possible to sort the ImageDatastore object itself, but you can certainly sort the filenames yourself: download my FEX submission natsortfiles, which was written to solve the exact file-order problem that you are having:
natsortfiles has plenty of examples in its help, the online description, and the HTML documentation, so you should not have any problems using it. You will probably have to specify the order of the files when calling ImageFileStore, by supplying the first argument as the correctly sorted filenames, something like this (untested):
D = 'D:\Google Drive\MARYLAND\ENPM808 Independent Study\Independent Study\3D_map_poses\rgb';
S = dir(fullfile(D,'*.png'));
N = natsortfiles({S.name});
F = cellfun(@(n)fullfile(D,n),N,'uni',0)
I = imageDatastore(F,...)
I don't have imageDatastore, so you will have to experiment with this yourself.
Note that you can easily avoid this whole problem by using adequate leading zeros on all of the filenames, e.g. use (0001).png instead of (1).png, then the filenames will always be sorted into the correct order.