How to gauss-filter (blur) a floating point numpy array

Robert Pollak picture Robert Pollak · Apr 28, 2015 · Viewed 52.2k times · Source

I have got a numpy array a of type float64. How can I blur this data with a Gauss filter?

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

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.

(I am using Pillow 2.7.0.)

Answer

Carsten picture Carsten · Apr 28, 2015

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.

from scipy.ndimage.filters import gaussian_filter

blurred = gaussian_filter(a, sigma=7)