Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting current element in scipy.ndimage.filters.generic_filter

Is it possible to get the "current element" inside scipy.ndimage.filters.generic_filter's filter function?

If, for example, A[0] always contained the current element (which doesn't seem to be the case) something like the following might find local maxima

def local_max_f(A) :
   return A[0] == A.max()

img = np.random.rand(100).reshape(10,10)
ndimage.generic_filter( img, local_max_f, size=3 )
like image 426
ajwood Avatar asked Oct 21 '22 02:10

ajwood


1 Answers

The current element should be the element in the centre of size (or A[1] in your example), but this can't be relied upon at the edges of the input array, and depends on the mode for handling array borders.

The docs instead provide a neat example (adapted for your situation below) for determining the current position in the filter using a class to maintain some state between iterations. This always iterates through the last dimension first; all you should have to do is replace the result line with whatever your filter function actually needs to do, in your case this would be something like result = self._array[self.coordinates] == buffer.max().

a = arange(12).reshape(3,4)

class fnc_class:
    def __init__(self, _array):
        # store the shape:
        self.shape = _array.shape
        self._array = _array
        # initialize the coordinates:
        self.coordinates = [0] * len(self.shape)

    def filter(self, buffer):
        result = self._array[tuple(self.coordinates)] == buffer.max()
        print self.coordinates
        # calculate the next coordinates:
        axes = range(len(self.shape))
        axes.reverse()
        for jj in axes:
            if self.coordinates[jj] < self.shape[jj] - 1:
                self.coordinates[jj] += 1
                break
            else:
                self.coordinates[jj] = 0
        return result

fnc = fnc_class(a)
generic_filter(a, fnc.filter, footprint = [[1, 0], [0, 1]])
like image 110
John Lyon Avatar answered Oct 27 '22 10:10

John Lyon