Hilbert transform with a sliding window
Maybe including some code containing an minimum working example would help. I didn't see any problem.

I tried this because I am interested in related questions and recently learned about the Hilbert transform. I also added some noise because noise is always there, but often neglected in answers to questions like this (a pet peeve of mine), even though it sometimes completely defeats certain methods. Here's what I get:



import numpy as np
import scipy.signal as sig
import matplotlib.pyplot as plt

# Parameters
N = 1300
t = np.arange(0,N)
f = 1.0/20

# Discontinuous amplitude envelope
A = np.ones(t.size)
A[1*t.size/5:2*t.size/5] = .2

# Time signal with noise
y = A*np.sin(2*np.pi*f*t)
y += (np.random.rand(N)*2-1)*.2

# Filter noise
filt = True
if filt :
    cutoff = int(N*f*1.5)
    yrms1 = (y**2).mean()**.5
    yF = np.fft.fft(y)
    yF[cutoff:]=0               # Filter
    y = np.real(np.fft.ifft(yF))
    yrms2 = (y**2).mean()**.5   # Keep signal energy
    y *= yrms1/yrms2

# Calculate envelope
envelope = np.abs(sig.hilbert(y));


# Plots
plt.figure(1, figsize=[10,7], dpi=100)
plt.clf()
plt.plot(A, label='Actual envelope')
plt.plot(y, label='Time signal')
plt.plot(envelope, '.', label='Calculated envelope')
plt.legend(loc='lower right')
plt.show()
plt.draw()
plt.pause(.1)




EDIT:
The demonstrates performance in a sliding window. Just replace the line with the envelope calculation above with this code. Note that the envelope at each location is only ever calculated using N_win surrounding points.

envelope = np.ones(N)*np.nan
N_win = 50      # needs at least twice the period or so
lag = 20        # needs to be &gt;= period. 
for i in range(N-N_win) :
    envelope[N_win+i-lag] = np.abs(sig.hilbert(y[i:i+N_win]))[-lag]




Note, that for my implementation of this to work well, you need to be looking ahead of where you are calculating the envelope by about 1 period. For real time processing, that means your 'envelope' signal will have to lag behind your main signal by at least one period. This is because of edge effects of the Hilbert transform. I don't think there is really any way around this.