2

我有这个代码(将图像读入一个巨大的矩阵)

allImages = [];
for ii = 1 : n
    img = imread( fileNames{ii} );
    img = imresize( rgb2gray(img), [100 100] );
    allImages = cat(3, allImages, img ); % append image to huge matrix
end

Matlab 将我指向循环中的最后一行,警告我在allIamges循环内增长。

那么这里有什么大不了的呢?

4

1 回答 1

6

这是一件大事。

就正确性而言 - 代码执行预期的操作。这里的问题是性能。

幕后会发生什么?

当一个新图像被添加到 .Matlab 时allImages Matlab 必须为调整大小的. 这通常需要为调整大小、复制旧数据和取消分配旧数据分配新的内存。 这些在后台发生的重新分配 + 复制操作(可能在每次迭代中!)可能非常耗时。allImagesallImagesallImages


可以做什么?

1. 预分配:如果你知道图片的数量和最终的大小allImages,提前预留这个空间:

allImages = zeros( 100, 100, n ); % pre-allocate, fill with zeros.
for ii = 1 : n
    % ...
    allImages(:,:, ii ) = img; % write into pre-allocated array
end

n2. 如果我事先不知道怎么办?: 有几个问题已经在处理这个问题。例如这个答案

于 2013-07-02T11:53:26.800 回答