Build a Sequential model | Computer Vision with Keras p.2

In this article, we will see how to build a sequential model with Keras. I advise you to see the previous lesson Create layers | Computer Vision with Keras p.1 before moving on.

In particular, we will see:
1. What is the sequential model
2. Basic conception of image preprocessing

1. What is the sequential model

The sequential model is less flexible than the functional API because the layers must be inserted one below the other and always used only with the same model. But it has the advantage of being easier to program.

First, we need to import Keras and create the model

import keras
from keras import layers

...

# Create a Sequantial Model
model = keras.Sequential()

As you can see, in a few lines the model is created. Now we need to add the layers. Within the layer, I have defined standard numbers of neurons but in general, there is no specific number and each case must be evaluated individually.

model.add(layers.Dense(32))
model.add(layers.Dense(16))
model.add(layers.Dense(2))

each layer is linked to the previous one based on its position. Now the input layer is missing but before defining it we have to prepare the image

2. Basics of image preprocessing

To pass the image to the sequential model of Keras we must first obtain some parameters: height, width, and the number of channels which in this case corresponds to three because the image is in BGR format.

Opencv image shape and 3 channel BGR

How do we get the parameters automatically?

The answer is simple, we use OpenCV

import cv2
import numpy as np

...

# Load and preprocess image
img = cv2.imread("red_panda.jpg")
height, width, channels = img.shape
print("Height: {}, Width: {}, Channels: {}".format(height, width, channels))

...

the shape and channel information is passed to the input layer. By adding these values the definition of the model becomes like this

# Create a Sequantial Model
model = keras.Sequential()
model.add(layers.Input(shape=(height, width, channels)))
model.add(layers.Dense(32))
model.add(layers.Dense(16))
model.add(layers.Dense(2))

Now we just have to pass the image to our sequential model but we cannot do it directly because the model is designed to process batches of images but in this example we are using only one. So we need to put the image into an array to get it processed.

preprocessed_img = np.array([img])

result = model(preprocessed_img)
print(result)

this is the result we get. A multidimensional array with several numbers. At the moment it does not matter what their meaning is because it is only an example but it is the demonstration that has correctly processed all the data.

sequential model with keras result
Blueprint

Learn to build Computer Vision Software easily and efficiently.

This is a FREE Workshop where I'm going to break down the 4 steps that are necessary to build software to detect and track any object.

Sign UP for FREE