在Python中应用均匀大小的中值滤波器
我的任务是将50x50像素大小的中值滤波器应用于图像。我知道如何应用过滤器,但是我怎么能指定过滤器的大小?我的代码到目前为止在下面。在Python中应用均匀大小的中值滤波器
import matplotlib.pyplot as plt
from astropy.io import fits
import scipy.signal as sg
# Open data files
hdulist = fits.open('xbulge-w1.fits')
w1data = hdulist[0].data
hdulist2 = fits.open('xbulge-w2.fits')
w2data = hdulist2[0].data
# Apply median filter to each image
w1_med = sg.medfilt(w1data)
w2_med = sg.medfilt(w2data)
# Set maximum sampled galactic lat (b) and long (l)
l_max = 15
b_max = 15
# Plot median filtered images, rescaled to galactic coordinates
plt.subplot2grid((2,1), (0,0))
plt.imshow(w1_med, origin='lower',
extent=[l_max, -l_max, -b_max, b_max],
cmap = 'gray')
plt.title('W1 median filter')
plt.subplot2grid((2, 1), (1,0))
plt.imshow(w2_med, origin='lower',
extent=[l_max, -l_max, -b_max, b_max],
cmap = 'gray')
plt.title('W2 median filter')
plt.tight_layout()
plt.show()
我看到这个定义medfilt:
Signature: sg.medfilt(volume, kernel_size=None) Docstring: Perform a median filter on an N-dimensional array. Apply a median filter to the input array using a local window-size given by `kernel_size`. Parameters ---------- volume : array_like An N-dimensional input array. kernel_size : array_like, optional A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of `kernel_size` should be odd. If `kernel_size` is a scalar, then this scalar is used as the size in each dimension. Default size is 3 for each dimension. ....
你试过吗?
sg.medfilt(w1data,kernel_size=50)
我在文档中看到了这一点,但它也表明kernel_size参数必须是奇数。我确实想知道是否让kernel_size = 49考虑了Python的从零开始的索引规则,但这与默认值3相比似乎很大。 – Jim421616
基于the docs我认为你需要改变的是
# Apply median filter to each image
w1_med = sg.medfilt(w1data)
w2_med = sg.medfilt(w2data)
到
# Apply median filter to each image
w1_med = sg.medfilt(w1data, kernel_size=50)
w2_med = sg.medfilt(w2data, kernel_size=50)
...为你做这项工作?
你的问题的关键是甚至内核的大小。 scipy.signal.medfilt
限制您使用奇数大小的内核。在Web上进行搜索,您会发现很多关于内核通常为奇数大小的信息。我相信主要原因在于集中。例如,如果您将包含具有偶数大小的高斯内核的高斯的图像进行卷积 - 则最终将得到与原始图像相比偏移(1/2像素)中心的高斯图像,没有卷入,形象。
关于中值滤波器具体而言,还有一个额外的原因可以考虑奇数大小的内核:具有奇数个像素会产生一个唯一的中值,而偶数个像素则需要决定,例如,开使用哪个像素作为结果:pixel[int(size/2)]
,pixel[int(size/2)+1]
或两者的平均值。
对于偶数内核,您不能使用scipy.signal.medfilt
。但是,您始终可以编写一个循环遍历输入图像的所有像素,并在每个像素“周围”提取一个尺寸均匀的窗口,然后计算该窗口中像素的中值。我引用了“around”,因为不清楚(=独特)如何将该窗口置于像素上:它将由您来决定。
根据你对一个答案的评论,我认为重要的是要突出内核的均匀性。 –