我有 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
有一些关于使用元胞数组与多维数组的讨论 in this post .通常,多维数组会为许多操作提供更好的性能,但需要连续的内存空间进行存储(这可能会导致您更快地达到内存限制以增加数组大小)。元胞数组不需要连续的内存空间,因此内存效率更高,但会使某些操作复杂化。
关于matlab - 查找矩阵单元格中所有索引的最大值和索引的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50823731/