簡體   English   中英

一維高斯卷積

[英]Convolution with a 1D Gaussian

我是卷積菜鳥,我在使用Python。 我正在嘗試將1D數組與1D高斯進行卷積,而我的數組是

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

高斯的FWHM為5。因此,我計算出的sigma為5/2.385 = ~2.09現在,我有2個選擇:

  1. 使用高斯的標准方程式生成高斯核,並使用np.convolve(array,Gaussian) 我使用的高斯方程

  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]

相對於等距數組(A)繪制的數組(B)基本上,我想將convolved arraynon-convolved數組與A一起繪制。 我該怎么做?

為什么numpy.convolvescipy.ndimage.gaussian_filter1d

這是因為這兩個函數對邊緣的處理方式不同; 至少是默認設置。 如果您在中心以一個簡單的峰值在其他任何地方都為零,那么結果實際上是相同的(如下所示)。 默認情況下, scipy.ndimage.gaussian_filter1d在邊緣反射數據,而numpy.convolve實際上將零填充以填充數據。 因此,如果在scipy.ndimage.gaussian_filter1d選擇默認值為cval=0mode='constant' ,並且在mode=same選擇numpy.convolve以產生相似的大小數組,則如下所示。

根據您要對數據進行的處理,必須決定如何處理邊緣。

關於如何繪制此圖形,我希望我的示例代碼對此進行解釋。

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()

提供以下圖像:

幾種卷積的“配置”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM