Search code examples
pythonscipyscipy.ndimage

Why is ndimage.maximum_filter not working a expected


I have a problem where I need to detect the local maximum of an image. I used the ndimage.maximum_filter to detect local maximas. Here is a sample code:

image = np.array([1,0,6,1,8,9,6,4])    

neigh = [1,0,1]

filtered_image = ndimage.maximum_filter(image, footprint=neigh, mode='constant', cval=np.inf)
print(f"filtered_image: {filtered_image}")

The code applies a 1D filter of size 3 on the image. This code gives me the following result:

filtered_image: [0 6 1 8 9 8 9 6]

The first element of the array is 0, and normally it should be np.inf. I don't know why is that the case.


Solution

  • It's a small bug, int images with cval=inf
    (np.array -> int or float or ..., depending on the types of the arg)

    import numpy as np
    from scipy import ndimage 
    
    image = np.array([1,0,6,1,8,9,6,4], dtype=float )
    neigh = [1,0,1]
    filtered_image = ndimage.maximum_filter( image, footprint=neigh,
        mode='constant', cval=np.inf )
    print(f"filtered_image: {filtered_image}")  # [inf 6 1 8 9 8 9 inf]