Find large number of consecutive values fulfilling condition in a numpy array

后端 未结 8 1551
悲&欢浪女
悲&欢浪女 2020-12-05 00:53

I have some audio data loaded in a numpy array and I wish to segment the data by finding silent parts, i.e. parts where the audio amplitude is below a certain threshold over

相关标签:
8条回答
  • 2020-12-05 01:49

    This should return a list of (start,length) pairs:

    def silent_segs(samples,threshold,min_dur):
      start = -1
      silent_segments = []
      for idx,x in enumerate(samples):
        if start < 0 and abs(x) < threshold:
          start = idx
        elif start >= 0 and abs(x) >= threshold:
          dur = idx-start
          if dur >= min_dur:
            silent_segments.append((start,dur))
          start = -1
      return silent_segments
    

    And a simple test:

    >>> s = [-1,0,0,0,-1,10,-10,1,2,1,0,0,0,-1,-10]
    >>> silent_segs(s,2,2)
    [(0, 5), (9, 5)]
    
    0 讨论(0)
  • 2020-12-05 01:52

    There is a very convenient solution to this using scipy.ndimage. For an array:

    a = array([1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0])
    

    which can be the result of a condition applied to another array, finding the contiguous regions is as simple as:

    regions = scipy.ndimage.find_objects(scipy.ndimage.label(a)[0])
    

    Then, applying any function to those regions can be done e.g. like:

    [np.sum(a[r]) for r in regions]
    
    0 讨论(0)
提交回复
热议问题