Menu

[r3211]: / trunk / py4science / examples / fft_imdenoise.py  Maximize  Restore  History

Download this file

75 lines (54 with data), 1.7 kB

 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
#!/usr/bin/env python
"""Image denoising example using 2-dimensional FFT."""
import sys
import numpy as N
import pylab as P
import scipy as S
def mag_phase(F):
"""Return magnitude and phase components of spectrum F."""
return (N.absolute(F), N.angle(F))
def plot_spectrum(F, amplify=1000):
"""Normalise, amplify and plot an amplitude spectrum."""
M = mag_phase(F)[0]
M *= amplify/M.max()
M[M > 1] = 1
P.imshow(M, P.cm.Blues)
try:
# Read in original image, convert to floating point for further
# manipulation
im = S.misc.pilutil.imread('data/moonlanding.jpg').astype(float)
except:
print "Could not open image."
sys.exit(-1)
# Compute the 2d FFT of the input image
F = N.fft.fft2(im)
# Now, make a copy of the original spectrum and truncate coefficients.
keep_fraction = 0.1
# Call ff a copy of the original transform. Numpy arrays have a copy method
# for this purpose.
ff = F.copy()
# Set r and c to be the number of rows and columns of the array.
r,c = ff.shape
# Set to zero all rows with indices between r*keep_fraction and
# r*(1-keep_fraction):
ff[r*keep_fraction:r*(1-keep_fraction)] = 0
# Similarly with the columns:
ff[:, c*keep_fraction:c*(1-keep_fraction)] = 0
# Reconstruct the denoised image from the filtered spectrum, keep only the real
# part for display
im_new = N.fft.ifft2(ff).real
# Show the results
P.figure()
P.subplot(221)
P.title('Original image')
P.imshow(im, P.cm.gray)
P.subplot(222)
P.title('Fourier transform')
plot_spectrum(F)
P.subplot(224)
P.title('Filtered Spectrum')
plot_spectrum(ff)
P.subplot(223)
P.title('Reconstructed Image')
P.imshow(im_new, P.cm.gray)
P.show()
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.