I am trying to write a code to implement discrete wavelet transform (haar wavelet dwt) without using packages in python.
So far I've found a link where they implemented something similar, the link Is this wavelet transform implementation correct?. It doesn't give any errors while running, but the end result isn't correct. The code I ran is :
def discreteHaarWaveletTransform(x):
N = len(x)
output = [0.0]*N
length = N >> 1
while True:
for i in range(0,length):
summ = x[i * 2] + x[i * 2 + 1]
difference = x[i * 2] - x[i * 2 + 1]
output[i] = summ
output[length + i] = difference
if length == 1:
return output
#Swap arrays to do next iteration
x = output[:length << 1]
length >>= 1
Input :
list=[56, 40, 8, 24, 48, 48, 40, 16]
Current output :
[280, -24, 64, 40, 16, -16, 0, 24]
Expected output :
[35, -3, 16, 10, 8, -8, 0, 12]
Is there something obvious I can't see?
Something like this should do the trick -- it's almost a literal translation of this answer for C. It probably means that this is not very Python-y code, but if you're not using
numpyfor this that's not very Python-y anyway.The main reason you did not get the output you expected is that you forgot to scale the output after filtering. This makes the coefficients at each next level approximately twice as high.
Mind that a scaling of ½ gives you the expected output, but a scaling of ½√2 is more commonly used, to preserve the L2-norm of signal under the wavelet transform.