使用MATLAB遍历指定的子文件夹及其下文件
2015-10-28 14:14
351 查看
文件目录结构
项目需要批量将图像导入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 all clc; clear; close all; %% Add all path global 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 ); end end
函数uigetdir
由于前面maindir需要指定路径,可能不是太方便。使用uigetdir可以方便的通过对话框选择文件夹,返回值为文件夹路径名。代码如下:
maindir = uigetdir( '选择一个文件夹' );
参考资料
[原]MATLAB遍历子文件夹及其下文件:http://m.blog.csdn.net/blog/u012675539/43671663
相关文章推荐
- 精确径向基(matlab工具箱)
- matlab程序移植到C(输出比较)
- Matlab 调用 C# dll
- c#向MATLAB传递字符串数组
- matlab绘制带有吴茶邦(error)的分组柱状图
- 使用matlab读取excel数据并保存
- Matlab boxplot for Multiple Groups(多组数据的箱线图)
- 使用matlab画不同填充图案的柱状图
- Matlab梯度下降及正规方程实现多变量的线性回归
- Matlab数值计算
- matlab的.dat文件读取
- 我的文件夹下面有汉字的路径,matlab 不识别
- papa的儿子 matlab plot3 color peaks
- 归并排序算法Matlab实现
- 【kate总结】matlab调用opencv出错总结
- 11.16 Matlab 生成可执行文件
- 径向基(matlab工具箱)
- matlab中的containers.Map()
- Matlab 函数记录本
- matlab学习