Finding local maxima/minima with Numpy in a 1D numpy array

后端 未结 12 1725
迷失自我
迷失自我 2020-11-22 15:13

Can you suggest a module function from numpy/scipy that can find local maxima/minima in a 1D numpy array? Obviously the simplest approach ever is to have a look at the neare

12条回答
  •  北海茫月
    2020-11-22 15:31

    Another solution using essentially a dilate operator:

    import numpy as np
    from scipy.ndimage import rank_filter
    
    def find_local_maxima(x):
       x_dilate = rank_filter(x, -1, size=3)
       return x_dilate == x
    
    

    and for the minima:

    def find_local_minima(x):
       x_erode = rank_filter(x, -0, size=3)
       return x_erode == x
    
    

    Also, from scipy.ndimage you can replace rank_filter(x, -1, size=3) with grey_dilation and rank_filter(x, 0, size=3) with grey_erosion. This won't require a local sort, so it is slightly faster.

提交回复
热议问题