我有100张图片,每张图片的大小分别为512 x 512,存储在单元格数组中。
我想通过搜索所有图像来找到每个像素位置的最大值和索引。
我的代码:
imgs = cell(1,5);
imgs{1} = [2,3,2;3,2,2;3,1,1];
imgs{2} = [2,3,1;4,2,3;2,2,1];
imgs{3} = [3,2,1;5,3,5;3,2,3];
imgs{4} = [4,4,2;5,3,4;4,2,2];
imgs{5} = [4,5,2;4,2,5;3,3,1];
[nrows, ncols] = size(imgs{1});
maxVal_Mat = zeros(nrows,ncols);
maxIdx_Mat = zeros(nrows,ncols);
for nrow = 1:nrows
for ncol = 1:ncols
[maxVal_Mat(nrow, ncol), maxIdx_Mat(nrow, ncol)] = max(cellfun(@(x) x(nrow, ncol) , imgs));
end
end
maxVal_Mat =
4 5 2
5 3 5
4 3 3
maxIdx_Mat =
4 5 1
3 3 3
4 5 3
关于如何优化此代码以节省执行时间和内存的任何想法。
注意:这是该问题的示例演示,原始像元和矩阵都很大。
谢谢,
戈皮
由于所有图像的大小均相同,因此将其存储在3D矩阵中比存储单元阵列更有意义,这也大大简化了对它们执行这样的操作。您可以将imgs
像元数组转换为3D矩阵,然后找到最大值和索引,如下所示:
imgs = cat(3, imgs{:}); % Concatenate into a 3D matrix
[maxValue, index] = max(imgs, [], 3) % Find max across third dimension
maxValue =
4 5 2
5 3 5
4 3 3
index =
4 5 1
3 3 3
4 5 3
在这篇文章中,有一些关于使用单元数组与多维数组的讨论。通常,多维数组可以为许多操作提供更好的性能,但是需要连续的内存空间来存储(这可能会导致您更快地达到内存限制,从而增加了数组大小)。单元阵列不需要连续的存储空间,因此可以提高存储效率,但是会使某些操作复杂化。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句