如何从多个imread变量创建3D矩阵?

时间:2013-05-11 07:15:05

标签: matlab matrix 3d

我正在尝试编写一个程序,该程序采用由多个png文件组成的矩阵,这些文件在矩阵中保存为子矩阵。我有10个相同大小的png文件保存为image_1,image_2等,我希望能够在稍后的循环中单独浏览每个图像。创建3D矩阵是最好的方法吗?如果是这样,我将如何在以后用于上述目的?

2 个答案:

答案 0 :(得分:0)

如果您只想从图像中创建3D矩阵,可以按以下方式执行操作:

>> image_1 = rand(5);
>> image_2 = rand(5);
>> [m, n] = size(image_1);
>> images = zeros(m, n, 2);
>> 
for ii=1:2
    eval(sprintf('images(:,:,%d) = image_%d;', ii, ii));
end
>> 

结果如下:

>> images

images(:,:,1) =

    0.9037    0.0305    0.6099    0.1829    0.1679
    0.8909    0.7441    0.6177    0.2399    0.9787
    0.3342    0.5000    0.8594    0.8865    0.7127
    0.6987    0.4799    0.8055    0.0287    0.5005
    0.1978    0.9047    0.5767    0.4899    0.4711


images(:,:,2) =

    0.0596    0.0967    0.6596    0.4538    0.1734
    0.6820    0.8181    0.5186    0.4324    0.3909
    0.0424    0.8175    0.9730    0.8253    0.8314
    0.0714    0.7224    0.6490    0.0835    0.8034
    0.5216    0.1499    0.8003    0.1332    0.0605

>> 

如果您认为之后不再需要单个image_ii变量,则可以按如下方式清除它们:

>> 
for ii=1:2
    eval(sprintf('clear image_%d;', ii));
end
>> 

新的3D矩阵稍后可能会用作images(:,:,1)images(4,3,2)等等。

答案 1 :(得分:0)

如果你知道图像的文件名格式,这很简单;例如:

directory = pwd; % select working directory (but could be anything)
Nimages = 5;

% Use a cell array to initially store results, 
% as we don't know how big the images are yet
myImages = cell(Nimages, 1); 

for iImg = 1:Nimages
    % Build file name
    imgFilename = sprintf('Image_%i', iImg);
    % Make it fully qualified using directory
    imgFilename = fullfile(directory, imgFilename);
    % Load the image
    myImages{iImg} = imread(imgFilename);
end

% This will convert from cell to 3D matrix:
myImages = cat(3, myImages{:})

您可以稍后使用

访问这些图像
myImages(:, :, n)

其中n是图像编号。