代码之家  ›  专栏  ›  技术社区  ›  Bilal

向路径字符串添加两位数以读取多个文件时出现问题

  •  0
  • Bilal  · 技术社区  · 6 年前

    我想从一个文件夹中读取多个文件,唯一的问题是 而不是拥有完整的映像路径:

    '检查板/高斯噪声/图像'u 01.jpg'

    我有最后两位没有零的路径

    编辑 :前9个图像路径上有空格而不是零。

    '检查板/高斯噪声/图像1.jpg'

    我该怎么解决这个问题

    %-------------------------------------------------------
    clc
    clear all
    close all
    %------------------------------------------------------
    path = 'checkboard/Gaussian_Noised/';
    % Define images to process
    imageFileNames = cell(1,36);
    for n = 1:36
    imageFileNames{n} = strcat(path,sprintf('image_%2d.jpg',n))
    end
    %------------------------------------------------------
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Max    6 年前

    在这种情况下,最好使用浮点格式说明符填充零:

    num2str(1,'%02.f')
    

    '01'年

    num2str(1,'%02.d')
    

    '1'

    num2str(1,'%2.d')
    

    '1'

    num2str(1,'%d')
    

    '1'

    所以在你的情况下:

    sprintf('image_%02.f.jpg',n)
    

    作为一般建议,您可能只需要检查文件夹中是否有特定模式的所有文件

    path2dir = pwd; % path to working directory
    pattern = 'image_*.jpg'
    Lst = dir(fullfile(path2dir ,pattern));
    for i = 1:length(Lst)
        path2file = fullfile(Lst(i).folder,Lst(i).name);
        % load the file and do something with it
    end