【问题标题】:How to set different stride with uniform filter in scipy?如何在 scipy 中使用统一过滤器设置不同的步幅?
【发布时间】:2020-12-20 14:39:57
【问题描述】:

我正在使用以下代码对我的数据运行统一过滤器:

from scipy.ndimage.filters import uniform_filter
a = np.arange(1000)
b = uniform_filter(a, size=10)

过滤器现在似乎可以像步幅设置为 // 2 一样工作。 如何调整代码让filter的stride不是大小的一半?

【问题讨论】:

    标签: scipy filtering signal-processing scipy.ndimage


    【解决方案1】:

    您似乎误解了uniform_filter 在做什么。

    在这种情况下,它会创建一个数组b,用以a[i] 为中心的大小为10 的块的平均值替换每个a[i]。所以,类似:

    for i in range(0, len(a)):  # for the 1D case
       b[i] = mean(a[i-10//2:i+10//2]
    

    请注意,这会尝试访问索引在 0..1000 范围之外的值。默认情况下,uniform_filter 假设位置 0 之前的数据只是之后数据的反映。最后也是类似的。

    还要注意b 使用与a 相同的类型。在a为整数类型的例子中,平均值也会以整数计算,这会导致一些精度损失。

    这里有一些代码和图表来说明正在发生的事情:

    import matplotlib.pyplot as plt
    import numpy as np
    from scipy.ndimage.filters import uniform_filter
    
    fig, axes = plt.subplots(ncols=2, figsize=(15,4))
    
    for ax in axes:
        if ax == axes[1]:
            a = np.random.uniform(-1,1,50).cumsum()
            ax.set_title('random curve')
        else:
            a = np.arange(50, dtype=float)
            ax.set_title('values from 0 to 49')
        b = uniform_filter(a, size=10)
    
        ax.plot(a, 'b-')
        ax.plot(-np.arange(0, 10)-1, a[:10], 'b:') # show the reflection at the start
        ax.plot(50 + np.arange(0, 10), a[:-11:-1], 'b:') # show the reflection at the end
        ax.plot(b, 'r-')
    plt.show()
    

    【讨论】:

    • 是的,我对过滤器的理解有误。最后的漂亮图表绝对是 +1!
    猜你喜欢
    • 1970-01-01
    • 2019-05-18
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    相关资源
    最近更新 更多