In [1]:
# lets blur a image by calculating the average of neighbor cells
from matplotlib import pyplot as plt
from matplotlib import image
import numpy as np
from scipy import ndimage
from __future__ import division
%matplotlib inline
In [2]:
# get image, use only red channel
img = image.imread('MP.tif')[...,0]
In [3]:
# neighbor mask/footprint
mask = np.array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
In [4]:
%%time
# take average of every cell
# here mode is how to handle border (default is mirror)
# mode=constant -> cval=const default 0
blur_img = ndimage.generic_filter(img, np.average, footprint=mask) #, mode='constant')
In [5]:
plt.figure(figsize=(13,13))
plt.imshow(blur_img, cmap='gray')
plt.figure()
plt.figure(figsize=(13,13))
plt.imshow(img, cmap='gray')
Out[5]:
Comparing the pictures, we see that the averaged picture have less noise. Lets look at a sample of the images and compare.
In [6]:
print img[120:130, 120:130]
print blur_img[120:130, 120:130]
In [7]:
print img.var()
print blur_img.var()
Variance is approximatly 200 less in the averaged image.
In [8]:
%%time
# use specific function convolve instead of generic_filter (speed)
blur_img2 = ndimage.convolve(img, mask/9.)
plt.figure(figsize=(13,13))
plt.imshow(blur_img2, cmap='gray')
In [9]:
np.array_equal(blur_img, blur_img2)
Out[9]:
In [10]:
print blur_img[120:130, 120:130]
print blur_img2[120:130, 120:130]
In [11]:
print blur_img.var()
print blur_img2.var()
Seems like some rounding error.
In [12]:
%%time
# +0.1 for rounding, then convert to uint8
blur_img2 = ndimage.convolve(img+0.1, mask/9.).astype(np.uint8)
plt.figure(figsize=(13,13))
plt.imshow(blur_img2, cmap='gray')
In [13]:
# check if they are the same
np.array_equal(blur_img, blur_img2)
Out[13]:
Now we save our refined function to common notebook and use it:
In [87]:
%run common.ipynb
smooth_img = smooth(img)
np.array_equal(blur_img, smooth_img)
Out[87]: