Rob*_*lak 19 python filtering numpy python-imaging-library
我有一个a
类型的numpy数组float64
.如何使用高斯滤波器模糊此数据?
我试过了
from PIL import Image, ImageFilter
image = Image.fromarray(a)
filtered = image.filter(ImageFilter.GaussianBlur(radius=7))
Run Code Online (Sandbox Code Playgroud)
,但这会产生ValueError: 'image has wrong mode'
.(它有模式F
.)
我可以通过乘以a
一些常数,然后舍入到整数来创建合适模式的图像.这应该有效,但我希望有一个更直接的方式.
(我正在使用Pillow 2.7.0.)
Car*_*ten 32
如果你有一个二维numpy数组a
,你可以直接在其上使用高斯滤镜,而不使用Pillow首先将它转换为图像.scipy有一个gaussian_filter
相同的功能.
from scipy.ndimage.filters import gaussian_filter
blurred = gaussian_filter(a, sigma=7)
Run Code Online (Sandbox Code Playgroud)
小智 12
使用卷积和高斯滤波器的可分离性的纯 numpy 解决方案为两个单独的滤波器步骤(这使得它相对较快):
kernel = np.array([1.0,2.0,1.0]) # Here you would insert your actual kernel of any size
a = np.apply_along_axis(lambda x: np.convolve(x, kernel, mode='same'), 0, a)
a= np.apply_along_axis(lambda x: np.convolve(x, kernel, mode='same'), 1, a)
Run Code Online (Sandbox Code Playgroud)
小智 6
这是我仅使用 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
Run Code Online (Sandbox Code Playgroud)