pythonscipyscipy.ndimage

scipy.ndimage.generic_filter1d not working


I am trying to use scipy.ndimage.generic_filter1d for the first time, but it's not going well. Here's what I'm trying

import numpy as np
from scipy.ndimage import generic_filter1d

def test(x):
    return x.sum()

im_cube = np.zeros((100,100,100))
calc = generic_filter1d(im_cube, test, filter_size=5, axis=2)

But I get this error:

TypeError: test() takes 1 positional argument but 2 were given

I'm using scipy 1.4.1 What am I doing wrong?

For the function, I also tried np.mean but then I got this:

TypeError: only integer scalar arrays can be converted to a scalar index

Solution

  • According to the documentation, the callback accepts two arguments: a reference to the input line, and a reference to the output line. It does not return the output, but rather modifies the provided buffer in-place.

    If you want to implement a rolling sum filter, you will need to do that somewhat manually. For example:

    def test(x, out)
        out[:] = np.lib.stride_tricks.as_strided(x, strides=x.strides * 2, shape=(5, x.size - 4)).sum(axis=0)
    

    To make it a mean, add / 5 at the end.

    The purpose of genetic_filter1d is to format the edges and run the outer loop. It does not actually implement the rolling filter for you. You are still required to implement the entire inner loop yourself.