Created
March 21, 2022 08:16
-
-
Save alexlib/5590585c78c0c73cb2ff9127195a9ab1 to your computer and use it in GitHub Desktop.
Attempts to build my own moving average background subtractor for pims
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 | |
def moving_average(a, n=5) : | |
""" creates moving average along the first axis of the | |
three dimensional numpy array, aka stack of images | |
""" | |
ret = np.cumsum(a, dtype=float, axis=0) | |
ret[n:,:,:] = ret[n:,:,:] - ret[:-n,:,:] | |
return ret[n - 1:,:,:] / n | |
from itertools import islice | |
def window(seq, n=2): | |
"Returns a sliding window (of width n) over data from the iterable" | |
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... " | |
it = iter(seq) | |
result = tuple(islice(it, n)) | |
if len(result) == n: | |
yield result | |
for elem in it: | |
result = result[1:] + (elem,) | |
yield result | |
# Martijn's version: | |
def moving_averages_SO(values, size): | |
for selection in window(values, size): | |
yield sum(selection) / size | |
from itertools import tee, islice | |
def nwise(iterable, n): | |
ts = tee(iterable, n) | |
for c, t in enumerate(ts): | |
next(islice(t, c, c), None) | |
return zip(*ts) | |
def moving_averages_nw(iterable, n): | |
yield from (sum(x)/n for x in nwise(iterable, n)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment