# Image blurring¶

In [1]:
import numpy as np
import matplotlib.pyplot as plt


Read in an image. PNG are easily supported, but the Python package PIL handles other formats.

Simply using imread and imshow will reveal that the image is in color (CMYK color space). This will be a $500\times 500\times 4$ double array. But let's collapse it by adding all of the colors.

In [2]:
I = plt.imread('alma.png')
I = I.sum(axis=-1)

In [10]:
A = np.random.rand(10,10)
plt.pcolor(A)

Out[10]:
<matplotlib.collections.PolyCollection at 0x1092538d0>
In [8]:
plt.figure(figsize=(12,12))
plt.imshow(I, cmap="gray")

Out[8]:
<matplotlib.image.AxesImage at 0x107697710>

Let's try something. Let's go to every pixel in the image a rewrite the grayscale of that pixel as the weighted average of its neighbors: $$pixel \leftarrow \frac{1}{8}\left( 4 pixel + pixel_{north} + pixel_{south} + pixel_{west} + pixel_{east}\right)$$

In [11]:
def blur(I):
for i in range(1,I.shape[0]-1):
for j in range(1,I.shape[1]-1):
I[i,j] = (4*I[i,j] + I[i-1,j] + I[i+1,j] + I[i,j-1] + I[i,j+1])/8.0
return I


Now time it!

In [13]:
%timeit blur(I)

1 loops, best of 3: 1.38 s per loop

In [12]:
blur(I)
blur(I)
blur(I)
plt.figure(figsize=(12,12))
plt.imshow(I, cmap="gray")

Out[12]:
<matplotlib.image.AxesImage at 0x10930add0>