I have a 3 dimensional numpy array, with shape Nx64x64. I would like to downsample it across dimensions 1 and 2 by taking the mean, resulting in a new array with shape Nx8x8.
I have a couple of working implementations, but I feel like there must be a neater way of doing it.
I initially tried to use np.split:
def subsample(inparray, n):
inp = inparray.copy()
res = np.moveaxis(np.array(np.hsplit(inp, inp.shape[1]/n)), 1, 0)
res = np.moveaxis(np.array(np.split(res, inp.shape[2]/n, axis=3)), 1, 0)
res = np.mean(res, axis=(3,4))
return res
I also tried using plain indexing:
def subsample2(inparray, n):
res = np.zeros((inparray.shape[0], n, n))
lin = np.linspace(0, inparray.shape[1], n+1).astype(int)
bounds = np.stack((lin[:-1], lin[1:]), axis=-1)
for i, b in enumerate(bounds):
for j, b2 in enumerate(bounds):
res[:, i, j] = np.mean(inparray[:, b[0]:b[1], b2[0]:b2[1]], axis=(1,2))
return res
I had wondered about using itertools.groupby, but it also looked quite involved.
Does anyone know of a clean solution?

所有评论(0)