Matlab:读取一个文件夹下多个子文件夹中的多个指定格式的文件
热爱生活的菇凉:
如果每个文件夹下的图片数量不相同,可以用元胞数组存,下面的代码中 用三个% 注释的部分是添加的用于存储的代码,可以参考一下。如果图片数量相等,也可以用三维数组。
[code=matlab]
clear;clc
% 确定包含多个子文件夹的总文件夹
maindir = 'D:\test';
% 再确定有哪些子文件夹,并过滤掉干扰的文件
subdir = dir( maindir ); % 确定子文件夹
%%% 添加下面两行代码
allImg = {}; % 空元胞
k = 1; % 存储的下标
for i = 1 : length( subdir )
if( isequal( subdir( i ).name, '.' ) || isequal( subdir( i ).name, '..' ) || ~subdir( i ).isdir ) % 如果不是目录跳过
continue;
end
% 找出子文件中的目标文件
subdirpath = fullfile( maindir, subdir( i ).name, '*.jpg' );
images = dir( subdirpath ); % 在这个子文件夹下找后缀为jpg的文件
% 对目标文件进行读取
for j = 1 : length( images )
imagepath = fullfile( maindir, subdir( i ).name, images( j ).name); % 文件所在路径
Img = imread(imagepath); % 读取文件
Img = imresize(Img,[96,160]); % 改变图片大小
%%% 读完以后存下来
allImg{k}{j} = Img;
end
%%% 存下一个文件夹下的图片数据
k = k + 1;
end
[/code]
|