matlab中的快速二维直方图 [英] fast 2dimensional histograming in matlab

查看:37
本文介绍了matlab中的快速二维直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have written a 2D histogram algorithm for 2 matlab vectors. Unfortunately, I cannot figure out how to vectorize it, and it is about an order of magnitude too slow for my needs. Here is what I have:

    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

想法?

谢谢!!约翰

推荐答案

这是我的 2D 直方图版本:

Here is my version for a 2D histogram:

%# 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,而不是分数").

Note that I removed the "non-negative" restriction, but kept integer bin centers (this could be easily changed into dividing range into equally-sized specified number of bins instead "fractions").

这主要受@SteveEddins 博客文章的启发

This was mainly inspired by @SteveEddins blog post.

这篇关于matlab中的快速二维直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆