gpt4 book ai didi

python - 与一维高斯卷积

转载 作者:行者123 更新时间:2023-12-02 20:15:06 25 4
gpt4 key购买 nike

我是卷积新手,我正在使用 Python。我正在尝试将一维数组与一维高斯进行卷积,我的数组是

B = [0.011,0.022,.032,0.027,0.025,0.033,0.045,0.063,0.09,0.13,0.17,0.21]

Gaussian 的 FWHM 是 5。所以我计算出 sigma 为 5/2.385 = ~2.09 现在,我有 2 个选项:

  1. 使用高斯标准方程生成高斯内核并使用 np.convolve(array, Gaussian) Gaussian equation I used

  2. 使用scipy.ndimage.gaussian_filter1d由于两者都是卷积任务,理论上两者都应该给出相似的输出。但事实并非如此。为什么会这样?

我附上了一张图片,我在其中绘制了阵列与另一个等距阵列的对比图

A = [1.0, 3.0, 5.0, 7.0, 9.0, 11.0, 13.0, 15.0, 17.0, 19.0, 21.0, 23.0]

The array (B) plotted against equally spaced array (A)基本上,我想将卷积数组非卷积 数组与A 一起绘制。我该怎么做?

最佳答案

为什么 numpy.convolvescipy.ndimage.gaussian_filter1d

这是因为两个函数处理边缘的方式不同;至少默认设置可以。如果你在中心取一个简单的峰,其他地方都为零,结果实际上是一样的(如下图所示)。默认情况下,scipy.ndimage.gaussian_filter1d 反射(reflect)边缘上的数据,而 numpy.convolve 实际上用零填充数据。因此,如果在 scipy.ndimage.gaussian_filter1d 中您选择了 mode='constant' 和默认值 cval=0numpy。在 mode=same 中卷积 以生成类似大小的数组,结果如下所示,相同。

根据您要对数据执行的操作,您必须决定应如何处理边缘。

关于如何绘制它,我希望我的示例代码能够解释这一点。

import matplotlib.pyplot as plt
import numpy as np
from scipy.ndimage.filters import gaussian_filter1d

def gaussian( x , s):
return 1./np.sqrt( 2. * np.pi * s**2 ) * np.exp( -x**2 / ( 2. * s**2 ) )

myData = np.zeros(25)
myData[ 12 ] = 1
myGaussian = np.fromiter( (gaussian( x , 1 ) for x in range( -3, 4, 1 ) ), np.float )
filterdData = gaussian_filter1d( myData, 1 )

myFilteredData = np.convolve( myData, myGaussian, mode='same' )
fig = plt.figure(1)

ax = fig.add_subplot( 2, 1, 1 )
ax.plot( myData, marker='x', label='peak' )
ax.plot( filterdData, marker='^',label='filter1D smeared peak' )
ax.plot( myGaussian, marker='v',label='test Gaussian' )
ax.plot( myFilteredData, marker='v', linestyle=':' ,label='convolve smeared peak' )
ax.legend( bbox_to_anchor=( 1.05, 1 ), loc=2 )

B = [0.011,0.022,.032,0.027,0.025,0.033,0.045,0.063,0.09,0.13,0.17,0.21]
myGaussian = np.fromiter( ( gaussian( x , 2.09 ) for x in range( -4, 5, 1 ) ), np.float )
bx = fig.add_subplot( 2, 1, 2 )
bx.plot( B, label='data: B' )
bx.plot( gaussian_filter1d( B, 2.09 ), label='filter1d, refl' )
bx.plot( myGaussian, label='test Gaussian' )
bx.plot( np.convolve( B, myGaussian, mode='same' ), label='Gaussian smear' )
bx.plot( gaussian_filter1d( B, 2.09, mode='constant' ), linestyle=':', label='filter1d, constant')
bx.legend( bbox_to_anchor=(1.05, 1), loc=2 )
plt.tight_layout()
plt.show()

提供以下图片:

Several convolve "configurations"

关于python - 与一维高斯卷积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52586395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com