我希望从文件夹中读取一组图像,然后将其存储在一个数组中,这样,如果我问imshow(imageArray(5))
,它将在数组中显示第5张图像。到目前为止,我使用从类似问题中发现的一些代码来做到这一点:
% Specify the folder where the files live.
myFolder = 'C:\Users\MyName\Documents\MATLAB\FolderName';
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.tif'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
imageArray = zeros(480, 1);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
% Now do whatever you want with this file name,
% such as reading it in as an image array with imread()
imageArray(k) = imread(fullFileName);
end
但是,当我这样做时,会出现以下错误:
无法执行分配,因为左侧和右侧都有一个 不同数量的元素。
ImportTry(第16行)中的错误imageArray(k)= imread(fullFileName);
有什么建议吗?谢谢:)
答案 0 :(得分:0)
该错误源于您使用零初始化数组的事实,因此图像的大小与数组元素的大小不对应。
您要使用cells。
所以您将初始化单元格:
imageCell = cell(480, 1);
,然后将图像分配给单元格数组的元素:
imageCell{k} = imread(fullFileName);
编辑: 正如Adriaan在他的answer中指出的那样,如果图像大小在文件夹中保持一致,则最好使用4D矩阵。
答案 1 :(得分:0)
代码的问题是,在循环的最后一行中,您将一个图像(其尺寸为1080x1920x3 uint8
(用于全高清图像))分配给大小为480x1
的矢量。这自然是行不通的。因此,请尝试以下操作并使用单元格数组。
% Specify the folder where the files live.
myFolder = 'C:\Users\MyName\Documents\MATLAB\FolderName';
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.tif'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
imageArray = cell(size(theFiles)); % initialize cell array for speedup
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
% Now do whatever you want with this file name,
% such as reading it in as an image array with imread()
imageArray(k) = {imread(fullFileName)};
end
% iterate cell array and display all images 1-by-1
for k = 1 : length(imageArray)
imshow(cell2mat(imageArray(k)))
pause; % press a button to continue
end
答案 2 :(得分:0)
与这里的其他解决方案相反,我不会去一个单元,因为众所周知,单元比矩阵要慢。我只是去一个4D矩阵,其中前三个是您的图像,即N行,M列,3个RGB通道,然后是图像的索引:
imageArray = zeros(N,M,3,480); % Where N and M are your image size
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
% Now do whatever you want with this file name,
% such as reading it in as an image array with imread()
imageArray(:,:,:,k) = imread(fullFileName);
end
请注意,这仅在所有图像都完全相同的形状时才有效。如果没有的话,细胞或结构是必经之路。