Book Image

Learning OpenCV 3 Computer Vision with Python (Update)

Book Image

Learning OpenCV 3 Computer Vision with Python (Update)

Overview of this book

Table of Contents (16 chapters)
Learning OpenCV 3 Computer Vision with Python Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
6
Retrieving Images and Searching Using Image Descriptors
Index

ANNs in OpenCV


Unsurprisingly, ANNs reside in the ml module of OpenCV.

Let's examine a dummy example, as a gentle introduction to ANNs:

import cv2
import numpy as np

ann = cv2.ml.ANN_MLP_create()
ann.setLayerSizes(np.array([9, 5, 9], dtype=np.uint8))
ann.setTrainMethod(cv2.ml.ANN_MLP_BACKPROP)

ann.train(np.array([[1.2, 1.3, 1.9, 2.2, 2.3, 2.9, 3.0, 3.2, 3.3]], dtype=np.float32),
  cv2.ml.ROW_SAMPLE,
  np.array([[0, 0, 0, 0, 0, 1, 0, 0, 0]], dtype=np.float32))

print ann.predict(np.array([[1.4, 1.5, 1.2, 2., 2.5, 2.8, 3., 3.1, 3.8]], dtype=np.float32))

First, we create an ANN:

ann = cv2.ml.ANN_MLP_create()

You may wonder about the MLP acronym in the function name; it stands for multilayer perceptron. By now, you should know what a perceptron is.

After creating the network, we need to set its topology:

ann.setLayerSizes(np.array([9, 5, 9], dtype=np.uint8))
ann.setTrainMethod(cv2.ml.ANN_MLP_BACKPROP)

The layer sizes are defined by the NumPy array that is passed into the setLayerSizes method. The...