Python 如何对浮点 numpy 数组进行高斯滤波(模糊)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29920114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to gauss-filter (blur) a floating point numpy array
提问by Robert Pollak
I have got a numpy array a
of type float64
. How can I blur this data with a Gauss filter?
我有一个 numpya
类型的数组float64
。如何使用高斯滤波器模糊这些数据?
I have tried
我试过了
from PIL import Image, ImageFilter
image = Image.fromarray(a)
filtered = image.filter(ImageFilter.GaussianBlur(radius=7))
, but this yields ValueError: 'image has wrong mode'
. (It has mode F
.)
,但这会产生ValueError: 'image has wrong mode'
。(它有模式F
。)
I could create an image of suitable mode by multiplying a
with some constant, then rounding to integer. That should work, but I would like to have a more direct way.
我可以通过乘以a
某个常数,然后舍入为整数来创建合适模式的图像。这应该有效,但我想有一个更直接的方法。
(I am using Pillow 2.7.0.)
(我使用枕头 2.7.0。)
采纳答案by Carsten
If you have a two-dimensional numpy array a
, you can use a Gaussian filter on it directly without using Pillow to convert it to an image first. scipy has a function gaussian_filter
that does the same.
如果你有一个二维的 numpy array a
,你可以直接在它上面使用高斯滤波器,而不用先用 Pillow 把它转换成图像。scipy 具有gaussian_filter
相同的功能。
from scipy.ndimage.filters import gaussian_filter
blurred = gaussian_filter(a, sigma=7)
回答by Filipe Alves
Here is my approach using only numpy. It is prepared with a simple 3x3 kernel, minor changes could make it work with custom sized kernels.
这是我仅使用 numpy 的方法。它是用一个简单的 3x3 内核准备的,稍作改动就可以使其与自定义大小的内核一起使用。
def blur(a):
kernel = np.array([[1.0,2.0,1.0], [2.0,4.0,2.0], [1.0,2.0,1.0]])
kernel = kernel / np.sum(kernel)
arraylist = []
for y in range(3):
temparray = np.copy(a)
temparray = np.roll(temparray, y - 1, axis=0)
for x in range(3):
temparray_X = np.copy(temparray)
temparray_X = np.roll(temparray_X, x - 1, axis=1)*kernel[y,x]
arraylist.append(temparray_X)
arraylist = np.array(arraylist)
arraylist_sum = np.sum(arraylist, axis=0)
return arraylist_sum