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

后端 未结 8 1572
悲&欢浪女
悲&欢浪女 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:27

    @joe-kington I've got about 20%-25% speed improvement over np.diff / np.nonzero solution by using argmax instead (see code below, condition is boolean)

    def contiguous_regions(condition):
        idx = []
        i = 0
        while i < len(condition):
            x1 = i + condition[i:].argmax()
            try:
                x2 = x1 + condition[x1:].argmin()
            except:
                x2 = x1 + 1
            if x1 == x2:
                if condition[x1] == True:
                    x2 = len(condition)
                else:
                    break
            idx.append( [x1,x2] )
            i = x2
        return idx
    

    Of course, your mileage may vary depending on your data.

    Besides, I'm not entirely sure, but i guess numpy may optimize argmin/argmax over boolean arrays to stop searching on first True/False occurrence. That might explain it.

提交回复
热议问题