'"Down-resolution" a numpy array
I have a numpy array of shape [5sx,5sy,5sz] and I’d like to create a tensor with shape [sx,sy,sz] where the value of each element is:
new_array[x,y,z] = mean(array[5x:5x+5,5y:5y+5,5z:5z+5])
I could do this in a loop, but is there a faster one-line approach?
(I'd really ideally like to do it where the size of the origin array is not an integer multiple of the new one, but that seems like a much harder question, and I thought this would be a good first step at least.)
Solution 1:[1]
You could use scikit-image block_reduce:
import numpy as np
import skimage.measure
arr5 = np.random.rand(20, 20, 20)
arr = skimage.measure.block_reduce(arr5, (5, 5, 5), np.mean)
print(f'arr.shape = {arr.shape}')
print(f'arr5[:5, :5, :5].mean() = {arr5[:5, :5, :5].mean()}')
print(f'arr[0, 0, 0] = {arr[0, 0, 0]}')
output:
arr.shape = (4, 4, 4)
arr5[:5, :5, :5].mean() = 0.47200241666948467
arr[0, 0, 0] = 0.4720024166694848
If you're dealing with large arrays and you have a GPU available I would advise you to look into pytorch's average pooling.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | yann ziselman |
