Renaming images random numbers that are located in several subdirectories

조회 수: 2 (최근 30일)
lreplo
lreplo 2015년 9월 11일
답변: Walter Roberson 2015년 9월 11일
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.

답변 (1개)

Walter Roberson
Walter Roberson 2015년 9월 11일
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.

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by