Created
March 1, 2012 23:04
-
-
Save nfaggian/1953870 to your computer and use it in GitHub Desktop.
Demonstrates how fourier transforms can be used to speed up a sliding window sum operation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import scipy.signal as signal | |
import scipy.ndimage as nd | |
import time | |
def slidingWindow(field, window): | |
""" | |
Gold standard sliding window operator. This slides along the field | |
and sums gridcells in a window. | |
@param field: nd-array of binary hits/misses. | |
@param window: window size, tuple. | |
""" | |
def accumulator(values): | |
return values.sum() | |
return nd.generic_filter( | |
field, | |
accumulator, | |
size=window, | |
mode='constant', | |
cval=0, | |
) | |
def fourierWindow(field, window): | |
""" | |
A fast sliding window operation that applies the convolution theorem. | |
@param field: nd-array of binary hits/misses. | |
@param window: window size, tuple. | |
""" | |
return signal.fftconvolve(field, np.ones(window), mode='same') | |
# Example of the difference in speed between approaches. | |
cube = np.ones((10, 200, 200)) | |
start = time.time() | |
fsum = slidingWindow(cube, (2, 40, 40)) | |
stop = time.time() | |
print 'Sliding window method: {} seconds'.format(stop - start) | |
start = time.time() | |
fsum = fourierWindow(cube, (2, 40, 40)) | |
stop = time.time() | |
print 'Fourier method: {} seconds'.format(stop - start) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment