-
Notifications
You must be signed in to change notification settings - Fork 0
/
fft.py
197 lines (154 loc) · 6.6 KB
/
fft.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import argparse
import math
import statistics
import time
import matplotlib.colors as colors
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
from scipy.sparse import csr_matrix, save_npz
from dft import DFT
def desiredSize(n):
p = int(math.log(n, 2))
return int(pow(2, p+1))
def compress_image(im_fft, compression_level, originalCount):
if compression_level < 0 or compression_level > 100:
AssertionError('compression_level must be between 0 to 100')
rest = 100 - compression_level
lower = np.percentile(im_fft, rest//2)
upper = np.percentile(im_fft, 100 - rest//2)
print('non zero values for level {}% are {} out of {}'.format(compression_level, int(
originalCount * ((100 - compression_level) / 100.0)), originalCount))
compressed_im_fft = im_fft * \
np.logical_or(im_fft <= lower, im_fft >= upper)
save_npz('coefficients-{}-compression.csr'.format(compression_level),
csr_matrix(compressed_im_fft))
return DFT.fast_two_dimension_inverse(compressed_im_fft)
def __main__():
results = None
try:
results = parseArgs()
except BaseException as e:
print("ERROR\tIncorrect input syntax: Please check arguments and try again")
return
mode = results.mode
image = results.image
# run tests
DFT.test()
if mode == 1:
# read the image
im_raw = plt.imread(image).astype(float)
# pad the image to desired size
old_shape = im_raw.shape
new_shape = desiredSize(old_shape[0]), desiredSize(old_shape[1])
im = np.zeros(new_shape)
im[:old_shape[0], :old_shape[1]] = im_raw
# perform fft 2d
fft_im = DFT.fast_two_dimension(im)
# display
fig, ax = plt.subplots(1, 2)
ax[0].imshow(im[:old_shape[0], :old_shape[1]], plt.cm.gray)
ax[0].set_title('original')
ax[1].imshow(np.abs(fft_im), norm=colors.LogNorm())
ax[1].set_title('fft 2d with lognorm')
fig.suptitle('Mode 1')
plt.show()
elif mode == 2:
# define a percentage keep fraction
keep_ratio = 0.08
# read the image
im_raw = plt.imread(image).astype(float)
# pad the image to desired size
old_shape = im_raw.shape
new_shape = desiredSize(old_shape[0]), desiredSize(old_shape[1])
im = np.zeros(new_shape)
im[:old_shape[0], :old_shape[1]] = im_raw
# perform fft 2d and remove high frequency values
fft_im = DFT.fast_two_dimension(im)
rows, columns = fft_im.shape
print("Fraction of pixels used {} and the number is ({}, {}) out of ({}, {})".format(
keep_ratio, int(keep_ratio*rows), int(keep_ratio*columns), rows, columns))
fft_im[int(rows*keep_ratio):int(rows*(1-keep_ratio))] = 0
fft_im[:, int(columns*keep_ratio):int(columns*(1-keep_ratio))] = 0
# perform ifft 2d to denoise the image
denoised = DFT.fast_two_dimension_inverse(fft_im).real
# display
fig, ax = plt.subplots(1, 2)
ax[0].imshow(im[:old_shape[0], :old_shape[1]], plt.cm.gray)
ax[0].set_title('original')
ax[1].imshow(denoised[:old_shape[0], :old_shape[1]], plt.cm.gray)
ax[1].set_title('denoised')
fig.suptitle('Mode 2')
plt.show()
elif mode == 3:
# read the image
im_raw = plt.imread(image).astype(float)
# pad the image to desired size
old_shape = im_raw.shape
new_shape = desiredSize(old_shape[0]), desiredSize(old_shape[1])
im = np.zeros(new_shape)
im[:old_shape[0], :old_shape[1]] = im_raw
originalCount = old_shape[0] * old_shape[1]
# define compression levels
compression = [0, 14, 30, 50, 70, 95]
# write down abs of fft
im_fft = DFT.fast_two_dimension(im)
# render
fig, ax = plt.subplots(2, 3)
for i in range(2):
for j in range(3):
compression_level = compression[i*3 + j]
im_compressed = compress_image(
im_fft, compression_level, originalCount)
ax[i, j].imshow(np.real(im_compressed)[
:old_shape[0], :old_shape[1]], plt.cm.gray)
ax[i, j].set_title('{}% compression'.format(compression_level))
fig.suptitle('Mode 3')
plt.show()
elif mode == 4:
# define sample runs
runs = 10
# run plots
fig, ax = plt.subplots()
ax.set_xlabel('problem size')
ax.set_ylabel('runtime in seconds')
ax.set_title('Line plot with error bars')
for algo_index, algo in enumerate([DFT.slow_two_dimension, DFT.fast_two_dimension]):
print("starting measurement for {}".format(algo.__name__))
x = []
y = []
problem_size = 2**4
while problem_size <= 2**12:
print("doing problem size of {}".format(problem_size))
a = np.random.rand(int(math.sqrt(problem_size)),
int(math.sqrt(problem_size)))
x.append(problem_size)
stats_data = []
for i in range(runs):
print("run {} ...".format(i+1))
start_time = time.time()
algo(a)
delta = time.time() - start_time
stats_data.append(delta)
mean = statistics.mean(stats_data)
sd = statistics.stdev(stats_data)
print("for problem size of {} over {} runs: mean {}, stdev {}".format(
problem_size, runs, mean, sd))
y.append(mean)
# ensure square and power of 2 problems sizes
problem_size *= 4
color = 'r--' if algo_index == 0 else 'g'
plt.errorbar(x, y, yerr=sd, fmt=color)
plt.show()
else:
print("ERROR\tMode {} is not recofgnized".format(mode))
return
def parseArgs():
parser = argparse.ArgumentParser()
parser.add_argument('-m', action='store', dest='mode',
help='Mode of operation 1-> fast, 2-> denoise, 3-> compress&save 4-> plot', type=int, default=1)
parser.add_argument('-i', action='store', dest='image',
help='image path to work on', type=str, default='moonlanding.png')
return parser.parse_args()
if __name__ == "__main__":
__main__()