-
Notifications
You must be signed in to change notification settings - Fork 2
/
fourier_transform.py
132 lines (92 loc) · 2.81 KB
/
fourier_transform.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import numpy as np
def DFT_1D(fx):
fx = np.asarray(fx, dtype=complex)
M = fx.shape[0]
fu = fx.copy()
for i in range(M):
u = i
sum = 0
for j in range(M):
x = j
tmp = fx[x]*np.exp(-2j*np.pi*x*u*np.divide(1, M, dtype=complex))
sum += tmp
# print(sum)
fu[u] = sum
# print(fu)
return fu
def inverseDFT_1D(fu):
fu = np.asarray(fu, dtype=complex)
M = fu.shape[0]
fx = np.zeros(M, dtype=complex)
for i in range(M):
x = i
sum = 0
for j in range(M):
u = j
tmp = fu[u]*np.exp(2j*np.pi*x*u*np.divide(1, M, dtype=complex))
sum += tmp
fx[x] = np.divide(sum, M, dtype=complex)
return fx
def FFT_1D(fx):
""" use recursive method to speed up"""
fx = np.asarray(fx, dtype=complex)
M = fx.shape[0]
minDivideSize = 4
if M % 2 != 0:
raise ValueError("the input size must be 2^n")
if M <= minDivideSize:
return DFT_1D(fx)
else:
fx_even = FFT_1D(fx[::2]) # compute the even part
fx_odd = FFT_1D(fx[1::2]) # compute the odd part
W_ux_2k = np.exp(-2j * np.pi * np.arange(M) / M)
f_u = fx_even + fx_odd * W_ux_2k[:M//2]
f_u_plus_k = fx_even + fx_odd * W_ux_2k[M//2:]
fu = np.concatenate([f_u, f_u_plus_k])
return fu
def inverseFFT_1D(fu):
""" use recursive method to speed up"""
fu = np.asarray(fu, dtype=complex)
fu_conjugate = np.conjugate(fu)
fx = FFT_1D(fu_conjugate)
fx = np.conjugate(fx)
fx = fx / fu.shape[0]
return fx
def FFT_2D(fx):
h, w = fx.shape[0], fx.shape[1]
fu = np.zeros(fx.shape, dtype=complex)
if len(fx.shape) == 2:
for i in range(h):
fu[i, :] = FFT_1D(fx[i, :])
for i in range(w):
fu[:, i] = FFT_1D(fu[:, i])
elif len(fx.shape) == 3:
for ch in range(3):
fu[:, :, ch] = FFT_2D(fx[:, :, ch])
return fu
def inverseDFT_2D(fu):
h, w = fu.shape[0], fu.shape[1]
fx = np.zeros(fu.shape, dtype=complex)
if len(fu.shape) == 2:
for i in range(h):
fx[i, :] = inverseDFT_1D(fu[i, :])
for i in range(w):
fx[:, i] = inverseDFT_1D(fx[:, i])
elif len(fu.shape) == 3:
for ch in range(3):
fx[:, :, ch] = inverseDFT_2D(fu[:, :, ch])
fx = np.real(fx)
return fx
def inverseFFT_2D(fu):
h, w = fu.shape[0], fu.shape[1]
fx = np.zeros(fu.shape, dtype=complex)
if len(fu.shape) == 2:
for i in range(h):
fx[i, :] = inverseFFT_1D(fu[i, :])
for i in range(w):
fx[:, i] = inverseFFT_1D(fx[:, i])
elif len(fu.shape) == 3:
for ch in range(3):
fx[:, :, ch] = inverseFFT_2D(fu[:, :, ch])
fx = np.real(fx)
return fx