Renaming images random numbers that are located in several subdirectories
2 views (last 30 days)
Show older comments
I have 1 directory and 63 subdirectory with images in each directory. I need to randomly assign them numbers WITHOUT repeating numbers for all of the images in the 1 directory. The problem I am having is renaming a .tif and a .png with randperm and numbers being reused because of this. I then move all the new images to one folder. See code below.
mainDirectory = '/Users/';
newDir = '/Users/Documents/Pictures/';
subDirectory = dir([mainDirectory '']);
for m = 1 : length(subDirectory)
subFolder1 = dir(fullfile(mainDirectory, subDirectory(m).name,'*.tif'));
subFolder2 = dir(fullfile(mainDirectory, subDirectory(m).name,'*.png'));
fileNames1 = {subFolder1.name};
fileNames2 = {subFolder2.name};
for iFile = 1 : numel( subFolder1 )
newName1 = fullfile(mainDirectory, subDirectory(m).name, sprintf( 'image%d.tif', randperm(256,1)));
movefile( fullfile(mainDirectory, subDirectory(m).name, fileNames1{ iFile }), newName1 );
copyfile(newName1,newDir)
end
for iFile = 1 : numel( subFolder2 )
newName2 = fullfile(mainDirectory, subDirectory(m).name, sprintf( 'image%d.png', randperm(256,1) ));
movefile( fullfile(mainDirectory, subDirectory(m).name, fileNames2{ iFile }), newName2 );
copyfile(newName2,newDir)
end
end
end
Thank you in advance.
0 Comments
Answers (1)
Walter Roberson
on 11 Sep 2015
Get one of the Recursive Directory tools from the File Exchange, such as http://www.mathworks.com/matlabcentral/fileexchange/40016-recursive-directory-searching-for-multiple-file-specs . Have it find all of the .png and .tif at the same time. You can then calculate how many there are in total, which gives you the range of values to randperm() over. You can use fileparts to pull apart each complete name to find the extension to prepare the destination file, and then you can movefile() or copyfile() from the source to the destination.
0 Comments
See Also
Categories
Find more on File Operations 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!