我正在访问以下文件夹中的图片:
"D:/images/c1"
"D:/images/c2"
"D:/images/c3"
每个文件夹有10张图片。我使用3 for循环来访问每个相应文件夹中的图像。我如何在单循环中完成它?
My Code:
srcFiles = dir('D:\Images\c1\*.ppm');
B = zeros(num_bins, 30);
ptr=1;
for i = 1 : length(srcFiles)
filename = strcat('D:\Images\c1\',srcFiles(i).name);
I = imread(filename);
B(:,ptr) = imcolourhist(I, num_red_bins, num_green_bins, num_blue_bins);
ptr=ptr+1;
end
for i = 1 : length(srcFiles)
filename = strcat('D:\Images\c2\',srcFiles(i).name);
I = imread(filename);
B(:,ptr) = imcolourhist(I, num_red_bins, num_green_bins, num_blue_bins);
ptr=ptr+1;
end
for i = 1 : length(srcFiles)
filename = strcat('D:\Images\c3\',srcFiles(i).name);
I = imread(filename);
B(:,ptr) =imcolourhist(I, num_red_bins, num_green_bins, num_blue_bins);
ptr=ptr+1;
end
答案 0 :(得分:1)
<强>代码强>
%// List all paths
path1 = 'D:/images/c1'
path2 = 'D:/images/c2'
path3 = 'D:/images/c3'
%// Get all paths into one cell array
paths = cellstr(cat(1,path1,path2,path3))
%// Get all filenames (with their full paths) into one cell array
filename1 = cell(numel(paths),1);
for k1=1:numel(paths)
filename1{k1} = fullfile(paths(k1),ls(char(fullfile(paths(k1),'*.ppm'))));
end
filenames = vertcat(filename1{:});
%// Your code modified according to the new path creating setup
B = zeros(num_bins, 30);
for k2 = 1 : numel(filenames)
I = imread(char(filenames(k2)));
B(:,k2) = imcolourhist(I, num_red_bins, num_green_bins, num_blue_bins);
end
<强>改进:强>
ptr
作为正在处理的文件名计数。答案 1 :(得分:0)
据我所知,每个循环之间的唯一区别是filename
。在这种情况下,您只需创建一个包含3个项目的数组(每个项目包含strcat
函数的前半部分)。然后,您可以使用嵌套for循环来实现所需的结果。
srcFiles = dir('D:\Images\c1\*.ppm');
B = zeros(num_bins, 30);
ptr=1;
sourceDir = ['D:\Images\c1\'; 'D:\Images\c2\'; 'D:\Images\c3\'];
for n = 1: length(sourceDir)
for i = 1 : length(srcFiles)
filename = strcat(sourceDir,srcFiles(i).name);
I = imread(filename);
B(:,ptr) = imcolourhist(I, num_red_bins, num_green_bins, num_blue_bins);
ptr=ptr+1;
end
end
自从我使用MATLAB以来已经大约4年了;所以,我并非100%确定我的语法正确。不过,这是使用的方法。