Lionel
Lionel

Reputation: 331

How to add a gaussian blur with a real gaussian shape on an image with Python

Let's say I have an image as the following 2D arrays:

img = np.array([
           [0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0],
           [0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0],
           [0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0],
           [0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0],
           [0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0],
           [0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0],
           [0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0],
           [0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0]])

I would like to apply a gaussian blur on it so the image would be as following :

imgBlurred = np.array([
           [0.0, 0.2, 0.7, 1, 0.7, 0.2, 0.3, 0.4, 0.5, 0.4, 0.3, 0.2, 0.1],
           [0.0, 0.2, 0.7, 1, 0.7, 0.2, 0.3, 0.4, 0.5, 0.4, 0.3, 0.2, 0.1],
           [0.0, 0.2, 0.7, 1, 0.7, 0.2, 0.3, 0.4, 0.5, 0.4, 0.3, 0.2, 0.1],
           [0.0, 0.2, 0.7, 1, 0.7, 0.2, 0.3, 0.4, 0.5, 0.4, 0.3, 0.2, 0.1],
           [0.0, 0.2, 0.7, 1, 0.7, 0.2, 0.3, 0.4, 0.5, 0.4, 0.3, 0.2, 0.1],
           [0.0, 0.2, 0.7, 1, 0.7, 0.2, 0.3, 0.4, 0.5, 0.4, 0.3, 0.2, 0.1],
           [0.0, 0.2, 0.7, 1, 0.7, 0.2, 0.3, 0.4, 0.5, 0.4, 0.3, 0.2, 0.1],
           [0.0, 0.2, 0.7, 1, 0.7, 0.2, 0.3, 0.4, 0.5, 0.4, 0.3, 0.2, 0.1]])

Basically, I would like a result where the gaussian is very thick for the ones values and larger for the 0.5 values in the original image.

Until now, I proceed as following:

 from scipy import ndimage
 import numpy as np
 #img is a numpy array
 imgBlurred = ndimage.filters.gaussian_filter(img, sigma=0.7)
 #Normalisation by maximal value, because the gaussian blur reduce the 1 to ~0.5
 imgBlurred = imgBlurred/imgBlurred.max()
 imgBlurred[imgBlurred > 1] = 1# In case of the maximal value was > 1

But doing this let the same larger for the ones and 0.5 on the blurred image. If someone know how to fix this "issue" I would like to have some advices !

Upvotes: 0

Views: 295

Answers (0)

Related Questions