Extract files with the same names in subfolders and save them into a new folder with a different name

조회 수: 66(최근 30일)
I have .png files with the same name stored in different folders. My goal is to rename and copy them into a new folder. The following code just saves the last image in the new folder. I am not able to figure out how to save PNG files with incremental values in name. I would appreciate any help. Thanks in advance.
myFolder = 'current folder path';
filePattern = fullfile(myFolder, '**/*.png');
theFiles = dir(filePattern);
numFiles = length(theFiles);
outputFolder = 'new folder path';
for K = 1 : numFiles
baseFileName = theFiles(K).name;
fullFileName = fullfile(theFiles(K).folder,baseFileName);
limages = imread(fullFileName);
fullFileName = fullfile(outputFolder, theFiles(K).name);
imwrite(limages,fullFileName);
end
  댓글 수: 2
Shourya
Shourya 2022년 4월 15일
편집: Shourya 2022년 4월 15일
@Walter Roberson Thank you for your response. There are no such requirements. I just want to retrieve and store all the files in a single folder. A number before the file extension with underscore is also fine. My files in subfolders are named as output_img.png.

댓글을 달려면 로그인하십시오.

채택된 답변

per isakson
per isakson 2022년 4월 15일
%%
myFolder = 'current folder path';
filePattern = fullfile(myFolder,'**','*.png');
theFiles = dir(filePattern);
numFiles = length(theFiles);
outputFolder = 'new folder path';
mkdir( outputFolder )
for K = 1 : numFiles
source_file = fullfile( theFiles(K).folder, theFiles(K).name );
target_name = sprintf( '%s_%03d.png', theFiles(K).name, K ); % less than 999 files
target_file = fullfile( outputFolder, target_name );
copyfile( source_file, target_file );
end
And some error handling and testing.
  댓글 수: 7

댓글을 달려면 로그인하십시오.

추가 답변(0개)

범주

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!

Translated by