【问题标题】:fast 2dimensional histograming in matlabmatlab中的快速二维直方图
【发布时间】:2011-10-10 07:03:34
【问题描述】:

我为 2 个 matlab 向量编写了一个 2D 直方图算法。不幸的是,我无法弄清楚如何对其进行矢量化,而且它对于我的需求来说太慢了一个数量级。这是我所拥有的:

    function [ result ] = Hist2D( vec0, vec1 )
%Hist2D takes two vectors, and computes the two dimensional histogram
% of those images.  It assumes vectors are non-negative, and bins
% are the integers.
%
%  OUTPUTS
%      result - 
%         size(result) = 1 + [max(vec0) max(vec1)]
%         result(i,j)  = number of pixels that have value 
%                             i-1 in vec0 and value j-1 in vec1.

    result = zeros(max(vec0)+1, max(vec1)+1);

    fvec0 = floor(vec1)+1;
    fvec1 = floor(vec0)+1;

    % UGH, This is gross, there has to be a better way...
    for i = 1 : size(fvec0);
        result(fvec0(i), fvec1(i)) = 1 + result(fvec0(i), fvec1(i));
    end
end

想法?

谢谢!! 约翰

【问题讨论】:

    标签: matlab 2d histogram


    【解决方案1】:

    你可以这样做:

    max0 = max(fvec0) + 1;
    max1 = max(fvec1) + 1;
    
    % Combine the vectors
    combined = fvec0 + fvec1 * max0;
    
    % Generate a 1D histogram
    hist_1d = hist(combined, max0*max1);
    
    % Convert back to a 2D histogram
    hist_2d = reshape(hist, [max0 max1]);
    

    (注:未经测试)

    【讨论】:

      【解决方案2】:

      这是我的二维直方图版本:

      %# some random data
      X = randn(2500,1);
      Y = randn(2500,1)*2;
      
      %# bin centers (integers)
      xbins = floor(min(X)):1:ceil(max(X));
      ybins = floor(min(Y)):1:ceil(max(Y));
      xNumBins = numel(xbins); yNumBins = numel(ybins);
      
      %# map X/Y values to bin indices
      Xi = round( interp1(xbins, 1:xNumBins, X, 'linear', 'extrap') );
      Yi = round( interp1(ybins, 1:yNumBins, Y, 'linear', 'extrap') );
      
      %# limit indices to the range [1,numBins]
      Xi = max( min(Xi,xNumBins), 1);
      Yi = max( min(Yi,yNumBins), 1);
      
      %# count number of elements in each bin
      H = accumarray([Yi(:) Xi(:)], 1, [yNumBins xNumBins]);
      
      %# plot 2D histogram
      imagesc(xbins, ybins, H), axis on %# axis image
      colormap hot; colorbar
      hold on, plot(X, Y, 'b.', 'MarkerSize',1), hold off
      

      请注意,我删除了“非负”限制,但保留了整数 bin 中心(这可以很容易地更改为将范围划分为大小相等的指定数量的 bin,而不是“分数”)。

      这主要是受到@SteveEddins blog post 的启发。

      【讨论】:

      • accumarray,为什么我不知道这个函数?惊人的!谢谢!
      • accumarray 在我的机器上运行时比我的方法快大约 30 倍。
      • @John:您可以在此处阅读有关被低估的 ACCUMARRAY 的更多信息:blogs.mathworks.com/loren/2008/02/20/…
      • 相当不错,但为什么要使用线性插值呢?您可以使用“最近”插值并跳过舍入和限制范围步骤。
      • @CarlWitthoft:对,histcounts 是我上面提到的histc 的现代替代品。
      猜你喜欢
      • 1970-01-01
      • 2016-06-17
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      相关资源
      最近更新 更多