【问题标题】:What filter do I need? Want to keep high frequency values only我需要什么过滤器?只想保留高频值
【发布时间】:2015-12-29 16:59:00
【问题描述】:

我问这个问题是因为我不太确定应该使用哪个过滤器。

我的只是一个由离散值组成的信号,例如s = [1 2 2 2 3 4 2 4 3 4 5 3 2 3 3]。然后,我想根据窗口大小过滤一个信号。所以例如如果我为s 使用 5 的窗口大小,那么我会得到; s_filtered = [2 2 2 2 2 4 4 4 4 4 3 3 3 3 3]。因此,我想保留每个块中频率最高的值。对于索引 0:4(窗口大小 5),最高频率的值为 2,所以我希望我的“过滤”信号(如果这确实是正确的术语)在“过滤”信号的所有索引 0:4 中都有 2 .

目前我只使用中值滤波器,但我认为这不是正确的方法。

这里有一些 python 代码来演示我在做什么(但如上所述,我认为这是错误的)。

import numpy as np
import pylab *
from scipy.signal import medfilt

test = np.random.randint(10, size=1000)

fig, ax1 = plt.subplots(1,sharey=True, sharex=True, figsize=(15,5))
ax1.plot(test)
ax1.plot(medfilt(test,[99]),'r')
plt.show()

红线是窗口大小为 99 的过滤信号。

解决方案:

import itertools
import collections

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return itertools.izip_longest(*args, fillvalue=fillvalue)

s = [1, 2, 2, 2, 3, 4, 2, 4, 3, 4, 5, 3, 2, 3, 3]

list(chain.from_iterable(repeat(collections.Counter(x).most_common(1)[0][0],5) for x in grouper(s,5)))

【问题讨论】:

  • 这是一道编程题?
  • 你能解释一下你想如何获得s_filtered吗?
  • 我只是把它写下来,因为这是我希望从给定信号(例如s)中得到的理想值。它不是以任何方式或方式计算的。
  • @Astrid 那么它背后的逻辑是什么?为什么你不保留 1 或 5???
  • 样本中最常见的值称为“众数”,是的,它是一种“平均值”。请参阅维基百科上的this

标签: python scipy filtering signal-processing


【解决方案1】:

您可以使用itertools recipes 中的grouper 函数根据指定的长度对数组进行分组,然后使用collections.Counter.most_common() 方法找到最常见的项目,并使用itertools.repeat 重复您的项目5 次和最后一个链itertools.chain.from_iterable 的重复对象:

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

演示:

>>> list(chain.from_iterable(repeat(Counter(x).most_common(1)[0][0],5) for x in grouper(s,5)))
[2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    相关资源
    最近更新 更多