Convolution Neural Network - Concept

In [1]:
import numpy as np
import keras

import imageio

import matplotlib.pyplot as plt
%matplotlib inline
Using TensorFlow backend.

Get an Image

In [6]:
url = "http://source.unsplash.com/U66avewmxJk/400x300"
In [7]:
cheetah = imageio.imread(url)
In [13]:
cheetah.shape
Out[13]:
(300, 400, 3)
In [8]:
plt.imshow(cheetah)
Out[8]:
<matplotlib.image.AxesImage at 0x7f1ceb43d5f8>
In [9]:
import skimage
In [10]:
image_gray = skimage.color.rgb2gray(cheetah)
In [14]:
image_gray.shape
Out[14]:
(300, 400)
In [12]:
plt.imshow(image_gray, cmap="gray")
Out[12]:
<matplotlib.image.AxesImage at 0x7f1cdaa00dd8>
In [30]:
image = image_gray.reshape(300, 400, 1)

What is a convolution?

In [16]:
from keras.models import Sequential
from keras.layers import Conv2D
In [33]:
filters = 1
kernal_size = (9,9)
In [34]:
model = Sequential()
model.add(Conv2D(filters, kernal_size, input_shape=(300,400,1)))
In [35]:
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_3 (Conv2D)            (None, 292, 392, 1)       82        
=================================================================
Total params: 82
Trainable params: 82
Non-trainable params: 0
_________________________________________________________________
In [36]:
#model.layers[0].get_weights()
In [37]:
def convolution(image, model):
    print("Original Shape:", image.shape)
    image = image / 255                  # Normalize the image 
    image_batch = np.array([image])      # Reshape to fit the model
    conv_image = model.predict(image_batch)
    conv_image = conv_image.squeeze()    # Get to back to shape
    print("New Shape:", conv_image.shape)
    plt.imshow(conv_image, cmap="gray")
In [38]:
convolution(image, model)
Original Shape: (300, 400, 1)
New Shape: (292, 392)

Pooling

In [40]:
from keras.layers import MaxPooling2D
In [41]:
model2 = Sequential()
model2.add(Conv2D(filters, kernal_size, input_shape=(300,400,1)))
model2.add(MaxPooling2D(pool_size=(2,2)))
In [42]:
convolution(image, model2)
Original Shape: (300, 400, 1)
New Shape: (146, 196)