python 中 (x,y) 点列表的移动平均线

Moving average on list of (x,y) points in python

我有一个点数组,[(x,​​y),...],是从用户鼠标画线中收集的,我想使用移动平均法去除其中的噪声。

我该怎么做?

这是一个使用 卷积 大小 s:

的示例
v = np.array([(0, 4), (1, 5), (2, 6), (-1, 9), (3, 7), (4, 8), (5, 9)])
s = 2

kernel = np.ones(s)
x = np.convolve(v[:,0], kernel, 'valid') / s
y = np.convolve(v[:,1], kernel, 'valid') / s
res = np.hstack((x[:, None], y[:, None]))

print(res)

输出:

[[0.5 4.5]
 [1.5 5.5]
 [0.5 7.5]
 [1.  8. ]
 [3.5 7.5]
 [4.5 8.5]]

s越大,路径越平滑。但是,s越大,路径越短

https://docs.scipy.org/doc/scipy/reference/signal.html#filtering

或者只使用 convolve 并在必要时更正边框

如果你的项目可以使用opencv,那就看 https://docs.opencv.org/4.5.2/d4/d86/group__imgproc__filter.html 并使用

a = np.array(list_of_points, 'f') # should be floating
kernel_size = 3 # for example
filtered = cv2.blur(a, (1, kernel_size), borderType=cv2.BORDER_REPLICATE)