'Convolution over only one axis of a multidimensional array (running mean over the frames of a video)

If I have a stack of 1D arrays, it is easy to get a running mean over the first axis:

import numpy as np
from scipy.ndimage import convolve1d
arr = np.random.random(size=(5000,10)) # a stack of 5000 1D arrays, each of length 10
running_mean = convolve1d(arr,np.ones(30)/30,axis=0) # replace each array by an average over 30 of them

However if I have a stack of 3D arrays, the obvious solutions become extremely slow

import numpy as np
arr = np.random.random(size=(5000,250,250,3)) # an rgb video with 5000 images, resolution 250x250
running_mean = np.array([arr[i:i+30].mean(0) for i in range(len(arr)-30)])

Is there a vectorized method in scipy, numpy, or opencv to convolve a kernel with a stack of arrays over only one axis?



Solution 1:[1]

You can still use convolve1d for your 3D array and just set the parameter axis accordingly.

Side note: Your method for the 3D array does not handle the case, when you reach the boundaries of the input array. So your output shape will be (4970, 250, 250, 3).

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