复制目录结构并处理图片

%% 复制文件夹结构(复制第一级文件夹及其子文件夹)
clear all;close all;clc

filepath = uigetdir('*.*','请选择要复制的第一级文件夹名称');
if filepath==0
    warndlg('请选择要复制的第一级文件夹名称');
end

directory = filepath ;%要复制的文件夹第一级目录名称
filepathSplit=split(filepath,'\');
splitPart=['\',char(filepathSplit(end))];%将第一级目录名称从路径中取出
S = regexp(filepath, splitPart, 'split');%以第一级目录名称为分割依据

answer=inputdlg('输入创建的文件名称','创建保存的文件夹名称');
filepathHead=strcat(char(S(1,1)),char(answer(1,1)));
 
folder{1}=directory;
flag=1; %1 when there are folders havenot be searched,0 otherwise
while flag
    currfolders=folder;
    folder={};
   
    for m=1:1:length(currfolders)
        direc=currfolders{m};
              
        allfiles=dir(direc);
        %the number of all the files in the current searching folder
        L=length(allfiles);
        %the number of folders to be searched on this class
        k=length(folder);
        for i=1:1:L
            if allfiles(i).isdir & (~strcmp(allfiles(i).name,'.')) & ~strcmp(allfiles(i).name,'..')
                k=k+1;
                folder{k}=[direc,filesep,allfiles(i).name];
                folder_name=[direc,filesep,allfiles(i).name];
                remain=folder_name;
                for j=1:length(filepathSplit)
                [token, remain] = strtok(remain,'\');
                end
                new_folder_name = strcat(filepathHead,remain);
                mkdir(new_folder_name);
            end
        end
    end
   
    %if there are no folders that havenot searched yet,flag=0 so the loop
    %will be ended
    if ~length(folder)
        flag=0;
    end
end

%% imadjust调整
%% 获得项目文件夹及其所有子文件夹(及子文件夹的子文件夹)的路径,存于数组path中。
p = genpath(filepath);% 获得文件夹data下所有子文件的路径,这些路径存在字符串p中,以';'分割
length_p = size(p,2);%字符串p的长度
path = {};%建立一个单元数组,数组的每个单元中包含一个目录
temp = [];
for i = 1:length_p %寻找分割符';',一旦找到,则将路径temp写入path数组中
    if p(i) ~= ';'
        temp = [temp p(i)];
    else
        temp = [temp '\']; %在路径的最后加入 '\'
        path = [path ; temp];
        temp = [];
    end
end
clear p length_p temp;
%%
oldFileName=char(filepathSplit(end));
newFileName=strcat(char(filepathSplit(end)),char(answer(1,1)));
file_num = size(path,1);% 子文件夹的个数
for i = 1:file_num
    file_path = path{i}; % 图像文件夹路径
    outputPath=strrep(path(i,1),oldFileName,newFileName);%保存路径
    img_path_list = dir(strcat(file_path,'\*.bmp'));%注意此处的图片格式可能不止一种:BMP,TIFF,jpg
%      img_path_list = dir(file_path);
    img_num = length(img_path_list); %该文件夹中图像数量
    %     frame_index = 0;
    if img_num > 0
        for j = 1:img_num
            %             frame_index = frame_index+1;
            image_name = img_path_list(j).name;% 图像名
            I =imread(strcat(file_path,'\',image_name));
            %% 图像处理过程
            J=imadjust(I);
            imshow(J);
            %% 存储   
            saveImgName= strcat(outputPath,image_name);            
            imwrite(J,char(saveImgName));
        end
    end
end
 

猜你喜欢

转载自blog.csdn.net/weixin_40699340/article/details/81219859