python

时间:2017-07-27 01:03:57

标签: python filtering

我想创建一个具有给定半径的圆形中值滤波器,而不是数组中的方形滤波器。 这是我到目前为止的尝试:

#   Apply median filter to each image
import matplotlib.pyplot as plt
radius = 25
disk_filter = plt.fspecial('disk', radius)
w1_median_disk = plt.imfilter(w1data, disk_filter, 'replicate')

w2_median_disk = plt.imfilter(w2data, disk_filter, 'replicate')

w1dataw2data是我正在尝试应用过滤器的2-d numpy数组。 fspecial模块来自Matlab,但我想在我的Python代码中使用它(或类似的东西)。有什么想法吗?

我收到错误消息“

  

disk_filter = plt.fspecial('disk',radius)
  AttributeError:'module'对象没有属性'fspecial'“

我想知道我是否可以导入包含fspecial的模块,或者是否包含Python中的等效命令。

3 个答案:

答案 0 :(得分:0)

刮刮摄影师'图片来自: https://www.mathworks.com/help/images/ref/fspecial.html

enter image description here

import numpy as np
import matplotlib.pyplot as plt

import os
from scipy import misc
path = 'D:/My Pictures/cameraman.bmp'
cameraman = misc.imread(path, flatten=0)

cameraman = np.average(cameraman, axis=2)

r = 10
y,x = np.ogrid[-r: r+1, -r: r+1]
disk = x**2+y**2 <= r**2
disk = disk.astype(float)

from scipy import signal
blur = signal.convolve2d(cameraman, disk, mode='full', boundary='fill', fillvalue=0)

import matplotlib 
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.imshow(cameraman, cmap = matplotlib.cm.Greys_r)
ax1.set_title('cameraman')
ax2.imshow(blur, cmap = matplotlib.cm.Greys_r)
ax2.set_title('signal.convolve2d(cameraman, disk..')

或者您可能希望使用scipy.ndimage.filters.convolve来反映&#39;边缘治疗

from scipy.ndimage.filters import convolve
blur = convolve(cameraman, disk)

答案 1 :(得分:0)

如果您愿意安装/使用其他软件包,我强烈建议您在Python中进行任何类型的图像处理都能获得惊人的skimage!使用类似磁盘的过滤器进行过滤只需两行代码:

import skimage
import skimage.data
import skimage.morphology
import skimage.filters

# load example image
original = skimage.data.camera()

# create disk-like filter footprint with given radius
radius = 10
circle = skimage.morphology.disk(radius)

# apply median filter with given footprint = structuring element = selem
filtered = skimage.filters.median(original, selem = circle)

答案 2 :(得分:0)

以下是我发现似乎可以完成工作的事情:

 from scipy.ndimage.filters import generic_filter as gf

 #   Define physical shape of filter mask
 def circular_filter(image_data, radius):
     kernel = np.zeros((2*radius+1, 2*radius+1))
     y, x = np.ogrid[-radius:radius+1, -radius:radius+1]
     mask = x**2 + y**2 <= radius**2
     kernel[mask] = 1                
     filtered_image = gf(image_data, np.median, footprint = kernel)
     return filtered_image

但我不确定我完全理解发生了什么。特别是,行是什么

     y, x = np.ogrid[-radius:radius+1, -radius:radius+1]
     mask = x**2 + y**2 <= radius**2
     kernel[mask] = 1

办?