如何从 MATLAB 中的两种不同类型的目录加载所有文件

How to load all files from a directory of two different types in MATLAB

我知道可以加载类型为 .gif 的所有文件,方法是:

files = dir('C:\myfolder\*.gif');

但是,我的问题是我想加载类型为 .gif.jpg 的所有文件。这样做的好方法是什么?

您可以简单地搜索 .gif.jpg 文件,然后一张一张地加载和处理图像。

只需调用 dir 两次 - 每种类型的图像调用一次,并将结果存储在两个单独的结构中。接下来,将所有文件名连接成一个结构,然后继续对所有图像进行处理。

像这样:

%// Specify the folder where your images are stored
folder = fullfile('path', 'to', 'your', 'folder');

%// Specify search pattern for JPEG and GIF files
jpgFileFolder = fullfile(folder, '*.jpg');
gifFileFolder = fullfile(folder, '*.gif');

%// Invoke dir for both types of images
d1 = dir(jpgFileFolder);
d2 = dir(gifFileFolder);

%// Concatenate both dir structures together into a single structure
d = [d1; d2];

%// For each image we have...
for idx = 1 : numel(d)
    %// Get full path to file
    f = fullfile(folder, d(idx).name);

    %// Read in the image
    im = imread(f);

    %// Do something with this image
    %//...
    %//...
end

fullfile 允许您创建一个 OS 独立的目录字符串。只需将属于字符串一部分的每个子目录作为单独的字符串参数放入 fullfile 中,它应该可以正常工作。