代码之家  ›  专栏  ›  技术社区  ›  Gopi

求矩阵单元中所有指数的最大值和指数的最佳方法

  •  7
  • Gopi  · 技术社区  · 6 年前

    我想通过搜索所有图像来查找每个像素位置的最大值和索引。

    imgs=cell(1,5);
    
    maxidx_mat=零(nrows,ncols);
    结束
    
    最大值=
    
    4 3 3 3
    
    
    3 3 3 3
    
    
    

    注意:这是问题的一个示例演示,原始单元格和矩阵非常大。

    enter image description here

    我的代码:

    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
    

    注意:这是问题的一个示例演示,原始单元格和矩阵相当大。

    果皮

    2 回复  |  直到 6 年前
        1
  •  3
  •   gnovice    6 年前

    imgs

    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 .通常,多维数组可以为许多操作提供更好的性能,但需要连续的内存空间来存储(这可能会使您更快地达到内存限制以增加数组大小)。单元数组不需要连续的内存空间,因此可以提高内存效率,但会使某些操作复杂化。

        2
  •  2
  •   obchardon    6 年前

    • 增加执行时间

    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];
    
    % Only for the first image
    Mmax = imgs{1};
    Mind = ones(size(imgs{1}));
    
    for ii = 2:numel(imgs)
        % 2 by 2 comparison
        [Mmax,ind] = max(cat(3,Mmax,imgs{ii}),[],3);
        Mind(ind == 2) = ii;
    end
    

    结果:

    Mmax =
    
       4   5   2
       5   3   5
       4   3   3
    
    Mind =
    
       4   5   1
       3   3   3
       4   5   3
    

    % your list of images
    file = {'a.img','b.img','c.img'}
    
    I = imread(file{1}); 
    Mmax = I;
    Mind = ones(size(I));
    
    for ii = 2:numel(file)
        I = imread(file{ii})
        [Mmax,ind] = max(cat(3,Mmax,I),[],3);
        Mind(ind == 2) = ii;
    end