【问题标题】:Faster copyfiles Matlab更快的复制文件 Matlab
【发布时间】:2018-01-16 17:15:24
【问题描述】:

我有一个文件夹 origin_training,其中包含 FMfolder1folder2... 等子文件夹。我可以将.png 格式的图像文件列表放入一个名为FM 的单元格中。

FM_dir = fullfile(origin_training, 'FM');
FM = struct2cell(dir(fullfile(FM_dir, '*.png')))';

我的目标是将文件夹中的名称与cd 中的图像匹配,并使用cd 中的图像创建一个新文件夹FM。两个路径中的图像名称相同。我可以这样做:

% mother_folder = '...' my current directory
filenames = FM(:,1);
destination = fullfile(mother_folder, 'FM', FM(:,1));
cellfun(@copyfile,filenames, destination);

这真的很慢。即使是少量图像 (~30) 也需要几分钟。

我的当前目录有大约 10000 张图像(对应于 FMfolder2folder3 的图像)。我在这里错过了什么?

【问题讨论】:

    标签: matlab file copy vectorization cell-array


    【解决方案1】:

    另一种方法是创建一个 shell 命令并执行它。假设FM 包含每个文件的完整路径,或者当前目录的相对路径,那么:

    FM_dir = fullfile(origin_training, 'FM');
    destination = fullfile(mother_folder, 'FM');
    curdir = cd(FM_dir);
    FM = dir('*.png');
    cmd = ['cp ', sprintf('%s ',FM.name), destination];
    system(cmd);
    cd(curdir);
    

    如果您使用的是 Windows,请将 'cp' 替换为 'copy'

    请注意,这里我们不是为每个要复制的文件创建一个 shell 命令(大概是 copyfile 所做的),而是一个一次性复制所有文件的 shell 命令。我们也没有指定每个复制文件的名称,我们指定要复制的文件的名称以及将它们复制到的位置。

    另请注意,要使其正常工作,mother_folder 必须是绝对路径。

    【讨论】:

      【解决方案2】:

      我以某种方式将我的代码放入一个函数中,现在它以预期的速度运行。我怀疑cd 与低速有关,所以我只将完整目录作为字符向量传递。 同样的方法适用于我的目的,或者稍作修改即可从A 复制到B。现在,它可以将A 中的文件与B 中的文件匹配并复制到B/folder_name

      function [out] = my_copyfiles(origin_dir, folder_name, dest_dir, extension)
      
      new_dir = fullfile(origin_dir, folder_name);
      
      % Get a cell with filenames in the origin_dir/folder_name
      % Mind transposing to have them in the rows
      NEW = struct2cell(dir(fullfile(new_dir, extension)))';
      
      dest_folder = fullfile(dest_dir, folder_name);
      
      % disp(dest_folder)
      
      if ~exist(dest_folder, 'dir')
      mkdir(dest_folder)
      end
      
      %% CAUTION, This is the step
      % Use names from NEW to generate fullnames in dest_dir that would match
      filenames = fullfile(dest_dir, NEW(:,1));
      destination = fullfile(dest_folder, NEW(:,1));
      
      % if you wanted from origin, instead run
      % filenames = fullfile(new_dir, NEW(:,1));
      
      % make the copies
      cellfun(@copyfile,filenames, destination);
      
      %Save the call
      
      out.originDir = new_dir;
      out.copyFrom = dest_dir;
      out.to = dest_folder;
      out.filenames = filenames;
      out.destination = destination;
      
      end
      

      【讨论】:

        猜你喜欢
        • 2011-07-15
        • 2020-10-12
        • 2018-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-24
        • 2015-09-30
        • 2014-03-31
        相关资源
        最近更新 更多