Debian Codegraph @

examples/01-filter/image_fft_perlin_noise.py

raw
1 """
2 .. _image_fft_perlin_noise_example:
3
4 Fast Fourier Transform with Perlin Noise
5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6
7 This example shows how to apply a Fast Fourier Transform (FFT) to a
8 :class:`pyvista.ImageData` using :func:`pyvista.ImageDataFilters.fft`
9 filter.
10
11 Here, we demonstrate FFT usage by first generating Perlin noise using
12 :func:`pyvista.sample_function() <pyvista.core.utilities.features.sample_function>` to
13 sample :func:`pyvista.perlin_noise <pyvista.core.utilities.features.perlin_noise>`,
14 and then performing FFT of the sampled noise to show the frequency content of
15 that noise.
16 """
17
18 import numpy as np
19 import pyvista as pv
20
21 # %%
22 # Generate Perlin Noise
23 # ~~~~~~~~~~~~~~~~~~~~~
24 # Start by generating some `Perlin Noise
25 # <https://en.wikipedia.org/wiki/Perlin_noise>`_ as in
26 # :ref:`perlin_noise_2d_example` example.
27 #
28 # Note that we are generating it in a flat plane and using a frequency of 10 in
29 # the x direction and 5 in the y direction. The unit of frequency is
30 # ``1/pixel``.
31 #
32 # Also note that the dimensions of the image are powers of 2. This is because
33 # the FFT is much more efficient for arrays sized as a power of 2.
34
35 freq = [10, 5, 0]
36 noise = pv.perlin_noise(1, freq, (0, 0, 0))
37 xdim, ydim = (2**9, 2**9)
38 sampled = pv.sample_function(noise, bounds=(0, 10, 0, 10, 0, 10), dim=(xdim, ydim, 1))
39
40 # warp and plot the sampled noise
41 warped_noise = sampled.warp_by_scalar()
42 warped_noise.plot(show_scalar_bar=False, text='Perlin Noise', lighting=False)
43
44
45 # %%
46 # Perform FFT of Perlin Noise
47 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~
48 # Next, perform an FFT of the noise and plot the frequency content.
49 # For the sake of simplicity, we will only plot the content in the first
50 # quadrant.
51 #
52 # Note the usage of :func:`numpy.fft.fftfreq` to get the frequencies.
53
54 sampled_fft = sampled.fft()
55 freq = np.fft.fftfreq(sampled.dimensions[0], sampled.spacing[0])
56 max_freq = freq.max()
57
58 # only show the first quadrant
59 subset = sampled_fft.extract_subset((0, xdim // 2, 0, ydim // 2, 0, 0))
60
61
62 # %%
63 # Plot the Frequency Domain
64 # ~~~~~~~~~~~~~~~~~~~~~~~~~
65 # Now, plot the noise in the frequency domain. Note how there is more high
66 # frequency content in the x direction and this matches the frequencies given
67 # to :func:`pyvista.perlin_noise <pyvista.core.utilities.features.perlin_noise>`.
68
69 # scale to make the plot viewable
70 subset['scalars'] = np.abs(subset.active_scalars)
71 warped_subset = subset.warp_by_scalar(factor=0.0001)
72
73 pl = pv.Plotter(lighting='three lights')
74 pl.add_mesh(warped_subset, cmap='blues', show_scalar_bar=False)
75 pl.show_bounds(
76 axes_ranges=(0, max_freq, 0, max_freq, 0, warped_subset.bounds[-1]),
77 xtitle='X Frequency',
78 ytitle='Y Frequency',
79 ztitle='Amplitude',
80 show_zlabels=False,
81 color='k',
82 font_size=26,
83 )
84 pl.add_text('Frequency Domain of the Perlin Noise')
85 pl.show()
86
87
88 # %%
89 # Low Pass Filter
90 # ~~~~~~~~~~~~~~~
91 # Let's perform a low pass filter on the frequency content and then convert it
92 # back into the space (pixel) domain by immediately applying a reverse FFT.
93 #
94 # When converting back, keep only the real content. The imaginary content has
95 # no physical meaning in the physical domain. PyVista will drop the imaginary
96 # content, but will warn you of it.
97 #
98 # As expected, we only see low frequency noise.
99
100 low_pass = sampled_fft.low_pass(1.0, 1.0, 1.0).rfft()
101 low_pass['scalars'] = np.real(low_pass.active_scalars)
102 warped_low_pass = low_pass.warp_by_scalar()
103 warped_low_pass.plot(
104 show_scalar_bar=False, text='Low Pass of the Perlin Noise', lighting=False
105 )
106
107
108 # %%
109 # High Pass Filter
110 # ~~~~~~~~~~~~~~~~
111 # This time, let's perform a high pass filter on the frequency content and then
112 # convert it back into the space (pixel) domain by immediately applying a
113 # reverse FFT.
114 #
115 # When converting back, keep only the real content. The imaginary content has no
116 # physical meaning in the pixel domain.
117 #
118 # As expected, we only see the high frequency noise content as the low
119 # frequency noise has been attenuated.
120
121 high_pass = sampled_fft.high_pass(1.0, 1.0, 1.0).rfft()
122 high_pass['scalars'] = np.real(high_pass.active_scalars)
123 warped_high_pass = high_pass.warp_by_scalar()
124 warped_high_pass.plot(
125 show_scalar_bar=False, text='High Pass of the Perlin Noise', lighting=False
126 )
127
128
129 # %%
130 # Sum Low and High Pass
131 # ~~~~~~~~~~~~~~~~~~~~~
132 # Show that the sum of the low and high passes equals the original noise.
133
134 grid = pv.ImageData(dimensions=sampled.dimensions, spacing=sampled.spacing)
135 grid['scalars'] = high_pass['scalars'] + low_pass['scalars']
136
137 print(
138 'Low and High Pass identical to the original:',
139 np.allclose(grid['scalars'], sampled['scalars']),
140 )
141
142 pl = pv.Plotter(shape=(1, 2))
143 pl.add_mesh(sampled.warp_by_scalar(), show_scalar_bar=False, lighting=False)
144 pl.add_text('Original Dataset')
145 pl.subplot(0, 1)
146 pl.add_mesh(grid.warp_by_scalar(), show_scalar_bar=False, lighting=False)
147 pl.add_text('Sum of the Low and High Passes')
148 pl.show()
149
150
151 # %%
152 # Animate
153 # ~~~~~~~
154 # Animate the variation of the cutoff frequency.
155
156
157 def warp_low_pass_noise(cfreq, scalar_ptp=None):
158 """Process the sampled FFT and warp by scalars."""
159 if scalar_ptp is None:
160 scalar_ptp = np.ptp(sampled['scalars'])
161 output = sampled_fft.low_pass(cfreq, cfreq, cfreq).rfft()
162
163 # on the left: raw FFT magnitude
164 output['scalars'] = output.active_scalars.real
165 warped_raw = output.warp_by_scalar()
166
167 # on the right: scale to fixed warped height
168 output_scaled = output.copy()
169 output_scaled['scalars_warp'] = (
170 output['scalars'] / np.ptp(output['scalars']) * scalar_ptp
171 )
172 warped_scaled = output_scaled.warp_by_scalar('scalars_warp')
173 warped_scaled.active_scalars_name = 'scalars'
174 # push center back to xy plane due to peaks near 0 frequency
175 warped_scaled.translate((0, 0, -warped_scaled.center[-1]), inplace=True)
176 # position it next to the left image
177 warped_scaled = warped_scaled.translate((-11, 11, 0), inplace=True)
178
179 return warped_raw + warped_scaled
180
181
182 # Initialize the plotter and plot off-screen to save the animation as a GIF.
183 pl = pv.Plotter(notebook=False, off_screen=True)
184 pl.open_gif('low_pass.gif', fps=8)
185
186 # add the initial mesh
187 init_mesh = warp_low_pass_noise(1e-2)
188 pl.add_mesh(init_mesh, show_scalar_bar=False, lighting=False, n_colors=128)
189 pl.camera.zoom(1.3)
190
191 for freq in np.geomspace(1e-2, 10, 15):
192 pl.clear()
193 mesh = warp_low_pass_noise(freq)
194 pl.add_mesh(mesh, show_scalar_bar=False, lighting=False, n_colors=128)
195 pl.add_text(f'Cutoff Frequency: {freq:.2f}', color='black')
196 pl.write_frame()
197
198 # write the last frame a few times to "pause" the gif
199 for _ in range(5):
200 pl.write_frame()
201
202 pl.close()
203
204
205 # %%
206 # The left mesh in the above animation warps based on the raw values of the FFT
207 # amplitude. This emphasizes how taking into account more and more frequencies
208 # as the animation progresses, we recover a gradually larger proportion of the
209 # full noise sample. This is why the mesh starts "flat" and grows larger as the
210 # frequency cutoff is increased.
211 #
212 # In contrast, the right mesh is always warped to the same visible height,
213 # irrespective of the cutoff frequency. This highlights how the typical
214 # wavelength (size of the features) of the Perlin noise decreases as the
215 # frequency cutoff is increased since wavelength and frequency are inversely
216 # proportional.
217 #
218 # .. tags:: filter