Convolution Neural Network

In [3]:
import numpy as np
import keras
import imageio
import matplotlib.pyplot as plt
%matplotlib inline
import vis

Lets get an image

In [8]:
url = "https://source.unsplash.com/U66avewmxJk/400x300"
In [9]:
cheetah = imageio.imread(url)
In [10]:
plt.imshow(cheetah)
Out[10]:
<matplotlib.image.AxesImage at 0x7f6c6751fda0>
In [11]:
import skimage
In [13]:
image_gray = skimage.color.rgb2gray(cheetah)
In [47]:
plt.imshow(image_gray, cmap="Blues");

What is a Convolution?

In [16]:
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Activation
In [38]:
filters = 1
kernel_size = (10,10)
In [39]:
model1 = Sequential()
model1.add(Conv2D(filters = filters, 
                  kernel_size= kernel_size,
                  input_shape=(300,400,1)))
In [40]:
model1.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_5 (Conv2D)            (None, 291, 391, 1)       101       
=================================================================
Total params: 101
Trainable params: 101
Non-trainable params: 0
_________________________________________________________________
In [41]:
#model1.layers[0].get_weights()
In [42]:
def convolution(image, model):
    print('Original Shape', image.shape)
    image = image / 255                     # normalise the image
    image_batch = np.array([image])         # Make the image an array
    conv_image = model.predict(image_batch) # Get the prediction
    conv_image = conv_image.squeeze()       # Get the new image
    print("New Shape", conv_image.shape)
    plt.imshow(conv_image, cmap="gray")
In [43]:
image = image_gray.reshape(300, 400, 1)
In [44]:
convolution(image, model1)
Original Shape (300, 400, 1)
New Shape (291, 391)

With Convolution + MaxPooling

In [49]:
model2 = Sequential()
model2.add(Conv2D(filters, kernel_size, input_shape=(300,400,1)))
model2.add(MaxPooling2D(pool_size=(4,4)))
In [50]:
convolution(image, model2)
Original Shape (300, 400, 1)
New Shape (72, 97)

Sub-Sample

In [52]:
plt.imshow(cheetah);
In [85]:
from keras.preprocessing.image import img_to_array, load_img, array_to_img
from PIL import Image
In [86]:
image = array_to_img(cheetah)
In [95]:
img = image.resize((100,150), PIL.Image.NEAREST )
In [96]:
plt.imshow(img)
Out[96]:
<matplotlib.image.AxesImage at 0x7f6c54063e48>