I have used voronoi binning: I have the central coordinates for each bin and I want to find the mean of all the pixels contained in each bin. I just can't get my head around how to slice the numpy array to vectorise it.
This is my current code: X and Y are 1D arrays with the x and y coordinates for the centre of each bin; f in the 2d image:
import numpy as np
from scipy.spatial import KDTree
def rebin(f, X, Y):
s = f.shape
x_grid = np.arange(s[0])
y_grid = np.arange(s[1])
x_grid, y_grid = np.meshgrid(x_grid,y_grid)
x_grid, y_grid = x_grid.flatten(), y_grid.flatten()
tree = KDTree(zip(X,Y))
_, b = tree.query(zip(x_grid, y_grid))
out = X*np.nan
for i in range(max(b)):
out[i] = np.nanmean(f[x_grid[b==i], y_grid[b==i]])
return out
The for-loop is currently a huge bottleneck. There is probably a really simple answer - I just can't see it at the moment!
can be replaced by two calls to
np.bincount
:or one call to
stats.binned_statistic
:For example,