Is there a way to apply a function over general slices of a multidimensional array?
As an example, given a 4D input array representing a color video [frame, y, x, color_channel]
, we would like to apply a 2D image filter to all 2D slices in [y, x]
.
Can this be expressed as a general operation apply_to_slices
as in the following?
video = np.random.rand(2, 3, 4, 3) # 2 frames, each 3x4 pixels with 3 channels.
def filter_2d(image): # example of simple 2D blur filter
import scipy.signal
kernel = np.ones((3, 3)) / 9.0
return scipy.signal.convolve2d(image, kernel, mode='same', boundary='symm')
def apply_to_slices(func, array, axes):
"""Apply 'func' to each slice of 'array', where a slice spans 'axes'.
Args:
func: function expecting an array of rank len(axes) and returning a
modified array of the same dimensions.
array: input of arbitrary shape.
axes: integer sequence specifying the slice orientation.
"""
pass
def non_general_awkward_solution(func, video):
new_video = np.empty_like(video)
for frame in range(video.shape[0]):
for channel in range(video.shape[3]):
new_video[frame, ..., channel] = func(video[frame, ..., channel])
return new_video
# new_video = apply_to_slices(filter_2d, video, axes=(1, 2))
new_video = non_general_awkward_solution(filter_2d, video)
print(video)
print(new_video)