如何在 MATLAB 中使用 for 循环加载一系列图像文件?
How to load a sequence of image files using a for loop in MATLAB?
我是 MATLAB 初学者。我想使用 for 循环在特定文件夹中加载 200 个图像文件(大小 192x192)。
图片名称为“1.png”、“2.png”、“3.png”等。
我的代码如下。
list = dir('C:/preds/*.png');
N = size(list,1);
sum_image = zeros(192,192,200);
for i = 1:N
sum_image(:,:,i) = imread('C:/preds/i.png');
end
我应该更改哪一部分?
我建议将循环内的行更改为以下内容:
sum_image(:,:,i) = imread(['C:/preds/', num2str(i), '.png']);
MATLAB 将字符串中的 i 视为字符,而不是变量 i。上面的代码行逐段构建您的字符串。
我可能会像下面的代码那样做:
您目前正在获取文件名列表,但实际上并没有对它做太多事情。迭代列表更安全,否则如果缺少数字,您可能会遇到问题。此外,排序可能是不必要的,具体取决于您的图像编号是否被零填充,以便它们以正确的顺序出现......但总比遗憾好。将数组初始化为大小 N
而不是硬编码 200 的另一个小更改。这将使其更加灵活。
searchDir = 'C:\preds\';
list = dir([searchDir '*.png']);
nameList = {list.name}; %Get array of names
imNum = str2double(strrep(nameList,'.png','')); %Get image number
[~,idx] = sort(imNum); %sort it
nameList = nameList(idx);
N = numel(nameList);
sum_image = zeros(192,192,N);
for i=1:N
sum_image(:,:,i) = imread(fullfile(searchDir,nameList{i}));
end
如果这不是家庭作业问题,那么这个问题的正确答案是不要将其写成 for 循环。使用 imageDatastore:
https://www.mathworks.com/help/matlab/ref/imagedatastore.html
ds = imageDatastore('C:/preds/');
sumImageCellArray = readall(ds);
sumImage = cat(3,sumImageCellArray{:});
我是 MATLAB 初学者。我想使用 for 循环在特定文件夹中加载 200 个图像文件(大小 192x192)。
图片名称为“1.png”、“2.png”、“3.png”等。
我的代码如下。
list = dir('C:/preds/*.png');
N = size(list,1);
sum_image = zeros(192,192,200);
for i = 1:N
sum_image(:,:,i) = imread('C:/preds/i.png');
end
我应该更改哪一部分?
我建议将循环内的行更改为以下内容:
sum_image(:,:,i) = imread(['C:/preds/', num2str(i), '.png']);
MATLAB 将字符串中的 i 视为字符,而不是变量 i。上面的代码行逐段构建您的字符串。
我可能会像下面的代码那样做:
您目前正在获取文件名列表,但实际上并没有对它做太多事情。迭代列表更安全,否则如果缺少数字,您可能会遇到问题。此外,排序可能是不必要的,具体取决于您的图像编号是否被零填充,以便它们以正确的顺序出现......但总比遗憾好。将数组初始化为大小 N
而不是硬编码 200 的另一个小更改。这将使其更加灵活。
searchDir = 'C:\preds\';
list = dir([searchDir '*.png']);
nameList = {list.name}; %Get array of names
imNum = str2double(strrep(nameList,'.png','')); %Get image number
[~,idx] = sort(imNum); %sort it
nameList = nameList(idx);
N = numel(nameList);
sum_image = zeros(192,192,N);
for i=1:N
sum_image(:,:,i) = imread(fullfile(searchDir,nameList{i}));
end
如果这不是家庭作业问题,那么这个问题的正确答案是不要将其写成 for 循环。使用 imageDatastore:
https://www.mathworks.com/help/matlab/ref/imagedatastore.html
ds = imageDatastore('C:/preds/');
sumImageCellArray = readall(ds);
sumImage = cat(3,sumImageCellArray{:});