[Numpy-discussion] 2-D Histogram

Andreas Hilboll lists at hilboll.de
Tue Sep 10 09:59:32 EDT 2013


On 10.09.2013 15:52, David Reed wrote:
> Hi there,
> 
> Is there a faster way to perform a 2D Histogram from a 2D matrix than
> what I have below:
> 
> def spatial_histogram(frame, n_bins):
> shape = frame.shape
> 
> h_len = shape[0]/n_bins
> w_len = shape[1]/n_bins
> 
> h_ind = range(0, shape[0], h_len)
> w_ind = range(0, shape[1], w_len)
> 
> max_val = 255*h_len*w_len
> 
> out = np.empty((n_bins, n_bins), np.uint8)
> 
> for ii in range(n_bins):
> for jj in range(n_bins):
> out[ii, jj] = np.sum(frame[h_ind[ii]:h_ind[ii]+h_len,
> w_ind[jj]:w_ind[jj]+w_len])/max_val*255
> 
> return out
> 
> Should I try implementing this in Cython, or is there something I can do
> in Numpy?
> 
> Thanks!

David,

are you aware of Scipy's binne_statistic_2d method?


http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binned_statistic_2d.html

At first glance it can do what you're trying to do.

Andreas.




More information about the NumPy-Discussion mailing list