Reputation: 125
Is there a python function that achieves resampling in the way MATLAB's resample() does? I've looked into scikits.samplerate's resample function but I'm not quite getting similar results.
Upvotes: 2
Views: 6148
Reputation: 1
I came across the same problem and developed this wrapper function, which performs exactly the same as the resample function in MATLAB.
def resample(x, p, q, n=10, beta=5):
from scipy.signal import upfirdn, lfilter, firwin
# anti-aliasing filter design
maxpq = max(p, q)
fc = 1 / maxpq
order = 2 * n * maxpq
b = firwin(order + 1, fc, window=('kaiser', beta))
b = p * b / np.sum(b)
# upsampling
x_us = upfirdn([1], x, p)
# anti-aliasing filtering
x_aa = lfilter(b, 1, np.hstack((x_us, np.zeros(q * n))))
# downsampling
x_ds = upfirdn([1], x_aa, 1, q)
x_ds = x_ds[n:]
return x_ds
Upvotes: 0
Reputation: 944
After looking at this for too long here's the best equivalent to matlab's resample(x,p,q):
x_resampled = resampy.resample(x, q, p, filter='sinc_window', window=scipy.signal.flattop)
For variance compared to the MATLAB results I'm seeing, 96.59 (length > 5000). As a comparison when I use scipy's 'resample',
resample_len = int(len(x) * p / q)+1
x_resampled = resample(x, resample_len , t=None, axis=0, window=None, domain='time')
I get a variance of 4,281.
Exploring the MATLAB method more, here's the description:
y = resample(x,p,q) resamples the input sequence, x, at p/q times the original sample rate. resample applies an FIR Antialiasing Lowpass Filter to x and compensates for the delay introduced by the filter. The function operates along the first array dimension with size greater than 1.
Where the FIR filter is:
p = 3;
q = 2;
maxpq = max(p,q);
fc = 1/maxpq;
n = 10;
order = 2*n*maxpq;
beta = 5;
b = fir1(order,fc,kaiser(order+1,beta));
b = p*b/sum(b);
I didn't discover a true 1-to-1 replacement, nor did I find one looking online or in ChatGPT.
Applying all the windows using window=scipy.signal.some_window, here's the name and variance:
boxcar 150.06
triang 102.92
blackman 107.66
hamming 117.09
hann 115.33
bartlett 102.91
flattop 96.59
parzen 103.51
bohman 106.08
blackmanharris 102.41
nuttall 102.71
barthann 111.97
cosine 127.05
exponential 13535.85
tukey 144.04
As you can see flattop performed the closest. If someone out there can get a better correlation to MATLAB's method please post it.
Upvotes: 0
Reputation: 63
The best function that is equivalent to MATLAB resample is as such:
MATLAB:
resample( Data_Low_Freq_v, Upsample_n ,Downsample_n );
Python:
import scipy.signal as ssg
ssg.resample_poly(Data_Low_Freq_v, Upsample_n, Downsample_n)
Upvotes: -1
Reputation: 46
There's a blog 'Audio Resampling in Python' about this. Both resampy and scipy.signal have a resample function implementation in different ways.
Upvotes: 3