使用MATLAB遍历指定的子文件夹及其下文件

来源:互联网 发布:mac 10.11.6 官方下载 编辑:程序博客网 时间:2024/06/06 05:39

文件目录结构

项目需要批量将图像导入Matlab,进行分类。

/maindir    |-- subdir1        |-- test1.bmp        |-- test2.bmp        |-- ...    |-- subdir2        |-- test3.bmp        |-- test4.bmp        |-- ...    |-- subdir3        |-- test5.bmp        |-- test6.bmp        |-- ...    |-- ...

主文件夹maindir下含有十个子文件夹,子文件夹分别包含多个图像bmp文件。


函数dir

可以使用函数dir,D = DIR(‘directory_name’)返回一个结构数组,包含了文件夹directory_name下的子文件夹和子文件的一些信息,第1个成员是文件名,第4个成员表示是否为文件夹。

%DIR List directory.%   DIR directory_name lists the files in a directory. Pathnames and%   wildcards may be used.  For example, DIR *.m lists all program files%   in the current directory.%%   D = DIR('directory_name') returns the results in an M-by-1%   structure with the fields: %       name    -- Filename%       date    -- Modification date%       bytes   -- Number of bytes allocated to the file%       isdir   -- 1 if name is a directory and 0 if not%       datenum -- Modification date as a MATLAB serial date number.%                  This value is locale-dependent.%%   See also WHAT, CD, TYPE, DELETE, LS, RMDIR, MKDIR, DATENUM.%%   Copyright 1984-2010 The MathWorks, Inc.%   Built-in function.

[注意] 要注意的是,第1个数组元素和第2个数组元素分别是’.’和’..’,表示当前目录和上层目录。


代码实现

%% clear allclc;clear;close all;%% Add all pathglobal matlabVisRoot;demo_path = [ matlabVisRoot '' ];addpath( demo_path );main_path = [ demo_path, 'MAINDIR/' ];%% Read all the images in the sub-files under LOGOS file.maindir = dir( main_path );for i = 1 : length( maindir )    % If maindir(i) is not a dir, skip    if( isequal( maindir( i ).name, '.' )||...        isequal( maindir( i ).name, '..')||...        ~maindir( i ).isdir)        continue;    end    % If maindir(i) is a dir, find the image files under the maindir(i).name    subdirpath = fullfile( logo_path, maindir( i ).name, '*.bmp' );    dat = dir( subdirpath );    % read the files under the subdirpath    for j = 1 : length( dat )        datapath = fullfile( logo_path, maindir( i ).name, dat( j ).name);        img = imread( datapath );    endend

函数uigetdir

由于前面maindir需要指定路径,可能不是太方便。
使用uigetdir可以方便的通过对话框选择文件夹,返回值为文件夹路径名。代码如下:

maindir = uigetdir( '选择一个文件夹' );

参考资料

[原]MATLAB遍历子文件夹及其下文件:
http://m.blog.csdn.net/blog/u012675539/43671663

0 0
原创粉丝点击