This notebook contains an excerpt from the book Machine Learning for OpenCV by Michael Beyeler. The code is released under the MIT license, and is available on GitHub.

Note that this excerpt contains only the raw code - the book is rich with additional explanations and illustrations. If you find this content useful, please consider supporting the work by buying the book!

A Taste of Machine Learning

So, you have decided to enter the field of machine learning. That's great!

Nowadays, machine learning is all around us—from protecting our email, to automatically tagging our friends in pictures, to predicting what movies we like. As a form of artificial intelligence, machine learning enables computers to learn through experience: to make predictions about the future using collected data from the past. On top of that, computer vision is one of today's most exciting application fields of machine learning, with deep learning and convolutional neural networks driving innovative systems such as self-driving cars and Google's DeepMind.

However, fret not; your application does not need to be as large-scale or world-changing as the previous examples in order to benefit from machine learning. In this chapter, we will talk about why machine learning has become so popular and discuss the kinds of problems that it can solve. We will then introduce the tools that we need in order to solve machine learning problems using OpenCV. Throughout the book, I will assume that you already have a basic knowledge of OpenCV and Python, but that there is always room to learn more. Are you ready then? Let's go!

You are reading the Jupyter Notebook version of Machine Learning for OpenCV by Michael Beyeler (Packt Publishing, 2017). Here you can find up-to-date versions of all the code in the book. Although some basic explanations are provided, the book itself contains a large number of illustrations and background information. If you find this content useful, please consider supporting the work by buying the book!

Installation

Before we get started, let's make sure that we have all the tools and libraries installed that are necessary to create a fully functioning data science environment. After downloading the latest code for this book from GitHub, we are going to install the following software:

  • Python's Anaconda distribution, based on Python 3.5 or higher
  • OpenCV 3.1 or higher
  • Some supporting packages

Don't feel like installing stuff? You can also visit http://beta.mybinder.org/v2/gh/mbeyeler/opencv-machine-learning/master, where you will find all the code for this book in an interactive, executable environment and 100% free and open source, thanks to the Binder project.

Getting the latest code for this book

You're looking at it!

To download the latest code for this book from GitHub, go to https://github.com/mbeyeler/opencv-machine-learning. There you can either download a .zip package (beginners) or clone the repository using git (intermediate users).

If you choose to go with git, the first step is to make sure it is installed (https://git-scm.com/downloads).

Then, open a terminal (or command prompt, as it is called in Windows):

  • On Windows 10, right-click on the Start Menu button, and select Command Prompt.
  • On Mac OS X, press Cmd + Space to open spotlight search, then type terminal, and hit Enter.
  • On Ubuntu and friends, press Ctrl + Alt + T. On Red Hat, right-click on the desktop and choose Open Terminal from the menu.

Navigate to a directory where you want the code downloaded, for example:

$ cd Desktop

Then you can grab a local copy of the latest code by typing the following:

$ git clone https://github.com/mbeyeler/opencv-machine-learning.git

This will download the latest code in a folder called opencv-machine-learning.

After a while, the code might change online. In that case, you can update your local copy by running the following command from within the opencv-machine-learning directory:

$ git pull origin master

Getting to grips with Python's Anaconda distribution

Anaconda is a free Python distribution developed by Continuum Analytics that is made for scientific computing. It works across Windows, Linux, and Mac OS X platforms and is free even for commercial use. However, the best thing about it is that it comes with a number of preinstalled packages that are essential for data science, math, and engineering. These packages include the following:

  • NumPy: A fundamental package for scientific computing in Python, which provides functionality for multidimensional arrays, high-level mathematical functions, and pseudo-random number generators
  • SciPy: A collection of functions for scientific computing in Python, which provides advanced linear algebra routines, mathematical function optimization, signal processing, and so on
  • scikit-learn: An open-source machine learning library in Python, which provides useful helper functions and infrastructure that OpenCV lacks
  • Matplotlib: The primary scientific plotting library in Python, which provides functionality for producing line charts, histograms, scatter plots, and so on
  • Jupyter Notebook: An interactive environment for the running of code in a web browser. The content you are reading right now is written in a Jupyter Notebook, hosted on GitHub, that you can view in your web browser. If you look at this content in a real Jupyter Notebook, it's not just static - you can run the code on your own machine!

An installer for your platform of choice (Windows, Mac OS X, or Linux) can be found on the Continuum website: https://www.continuum.io/Downloads. I recommend using the Python 3.6 based distribution, since Python 2 is no longer under active development.

To run the installer, do one of the following:

  • On Windows, simply double-click the .exe file and follow the instructions on the screen.
  • On Mac OS X, double-click the .pkg file and follow the instructions on the screen.
  • On Linux, open a terminal and run the .sh script using bash:
    $ bash Anaconda3-4.3.0-Linux-x86_64.sh # for Python 3.6 based Anaconda
    
    $ bash Anaconda2-4.3.0-Linux-x64_64.sh # for Python 2.7 based Anaconda

After successful installation, you can install new packages on the terminal using the following command:

$ conda install package_name

where package_name is the actual name of the package to be installed.

Existing packages can be updated using:

$ conda update package_name

We can also search for packages using the following command:

$ anaconda search -t conda package_name

This will bring up a long list of users who have OpenCV packages installed, where we can locate users that have our version of the software installed on our own platform. A package called package_name from a user called user_name can then be installed as follows:

$ conda install -c user_name package_name

Finally, conda provides something called an environment, which allows us to manage different versions of Python and/or packages installed in them. This means we could have one environment where we have all packages necessary to run OpenCV 2.4 with Python 2.7, and another where we run OpenCV 3.2 with Python 3.6. In the following section, we will create an environment that contains all the packages needed to run the code in this book.

Installing OpenCV in a conda environment

In a terminal, navigate to the directory where you downloaded the code:

$ cd Desktop/opencv-machine-learning

Before we create a new conda environment, we want to make sure we added the Conda- Forge channel to our list of trusted conda channels:

$ conda config --add channels conda-forge

The Conda-Forge channel is led by an open-source community that provides a wide variety of code recipes and software packages (for more info, see https://conda-forge.github.io). Specifically, it provides an OpenCV package for 64-bit Windows, which will simplify the remaining steps of the installation.

Then run the following command to create a conda environment based on Python 3.5, which will also install all the necessary packages listed in the file requirements.txt in one fell swoop:

$ conda create -n Python3 python=3.5 --file requirements.txt

To activate the environment, type one of the following, depending on your platform:

$ source activate Python3 # on Linux / Mac OS X

$ activate Python3 # on Windows

Once we close the terminal, the session will be deactivated—so we will have to run this last command again the next time we open a terminal. We can also deactivate the environment by hand:

$ source deactivate # on Linux / Mac OS X

$ deactivate # on Windows

And done!

Verifying the installation

It’s a good idea to double-check your installation. While our terminal is still open, we fire up IPython, which is an interactive shell to run Python commands:

$ ipython

Now make sure that you are running (at least) Python 3.5 and not Python 2.7. You might see the version number displayed in IPython's welcome message. If not, you can run the following commands:


In [1]:
import sys
print(sys.version)


3.5.3 | packaged by conda-forge | (default, May 12 2017, 15:07:14) 
[GCC 4.8.2 20140120 (Red Hat 4.8.2-15)]

Now try to import OpenCV:


In [2]:
import cv2

You should get no error messages. Then try to find out the version number:


In [3]:
cv2.__version__


Out[3]:
'3.1.0'

Make sure that the Python version reads 3.5 or 3.6, but not 2.7. Additionally, make sure that OpenCV's version number reads at least 3.1.0; otherwise, you will not be able to use some OpenCV functionality later on.

You can then exit the IPython shell by typing exit - or hitting Ctrl + D and confirming that you want to quit.

Alternatively, you can run the code in a web browser thanks to Jupyter Notebook. If you have never heard of Jupyter Notebooks or played with them before, trust me - you will love them! If you followed the directions as mentioned earlier and installed the Python Anaconda stack, Jupyter is already installed and ready to go. In a terminal, type as follows:

$ jupyter notebook

This will automatically open a browser window, showing a list of files in the current directory. Click on the opencv-machine-learning folder, then on the notebooks folder, and voila! Here you will find all the code for this book, ready for you to be explored.

Check out pages 20 and 21 in the book to find helpful tips about how to navigate a Jupyter Notebook!

Getting a glimpse of OpenCV's ML module

Starting with OpenCV 3.1, all machine learning-related functions in OpenCV have been grouped into the ml module. This has been the case for the C++ API for quite some time.

You can get a glimpse of what's to come by displaying all functions in the ml module:


In [4]:
dir(cv2.ml)


Out[4]:
['ANN_MLP_BACKPROP',
 'ANN_MLP_GAUSSIAN',
 'ANN_MLP_IDENTITY',
 'ANN_MLP_NO_INPUT_SCALE',
 'ANN_MLP_NO_OUTPUT_SCALE',
 'ANN_MLP_RPROP',
 'ANN_MLP_SIGMOID_SYM',
 'ANN_MLP_UPDATE_WEIGHTS',
 'ANN_MLP_create',
 'BOOST_DISCRETE',
 'BOOST_GENTLE',
 'BOOST_LOGIT',
 'BOOST_REAL',
 'Boost_DISCRETE',
 'Boost_GENTLE',
 'Boost_LOGIT',
 'Boost_REAL',
 'Boost_create',
 'COL_SAMPLE',
 'DTREES_PREDICT_AUTO',
 'DTREES_PREDICT_MASK',
 'DTREES_PREDICT_MAX_VOTE',
 'DTREES_PREDICT_SUM',
 'DTrees_PREDICT_AUTO',
 'DTrees_PREDICT_MASK',
 'DTrees_PREDICT_MAX_VOTE',
 'DTrees_PREDICT_SUM',
 'DTrees_create',
 'EM_COV_MAT_DEFAULT',
 'EM_COV_MAT_DIAGONAL',
 'EM_COV_MAT_GENERIC',
 'EM_COV_MAT_SPHERICAL',
 'EM_DEFAULT_MAX_ITERS',
 'EM_DEFAULT_NCLUSTERS',
 'EM_START_AUTO_STEP',
 'EM_START_E_STEP',
 'EM_START_M_STEP',
 'EM_create',
 'KNEAREST_BRUTE_FORCE',
 'KNEAREST_KDTREE',
 'KNearest_BRUTE_FORCE',
 'KNearest_KDTREE',
 'KNearest_create',
 'LOGISTIC_REGRESSION_BATCH',
 'LOGISTIC_REGRESSION_MINI_BATCH',
 'LOGISTIC_REGRESSION_REG_DISABLE',
 'LOGISTIC_REGRESSION_REG_L1',
 'LOGISTIC_REGRESSION_REG_L2',
 'LogisticRegression_BATCH',
 'LogisticRegression_MINI_BATCH',
 'LogisticRegression_REG_DISABLE',
 'LogisticRegression_REG_L1',
 'LogisticRegression_REG_L2',
 'LogisticRegression_create',
 'NormalBayesClassifier_create',
 'ROW_SAMPLE',
 'RTrees_create',
 'STAT_MODEL_COMPRESSED_INPUT',
 'STAT_MODEL_PREPROCESSED_INPUT',
 'STAT_MODEL_RAW_OUTPUT',
 'STAT_MODEL_UPDATE_MODEL',
 'SVM_C',
 'SVM_CHI2',
 'SVM_COEF',
 'SVM_CUSTOM',
 'SVM_C_SVC',
 'SVM_DEGREE',
 'SVM_EPS_SVR',
 'SVM_GAMMA',
 'SVM_INTER',
 'SVM_LINEAR',
 'SVM_NU',
 'SVM_NU_SVC',
 'SVM_NU_SVR',
 'SVM_ONE_CLASS',
 'SVM_P',
 'SVM_POLY',
 'SVM_RBF',
 'SVM_SIGMOID',
 'SVM_create',
 'StatModel_COMPRESSED_INPUT',
 'StatModel_PREPROCESSED_INPUT',
 'StatModel_RAW_OUTPUT',
 'StatModel_UPDATE_MODEL',
 'TEST_ERROR',
 'TRAIN_ERROR',
 'TrainData_create',
 'TrainData_getSubVector',
 'VAR_CATEGORICAL',
 'VAR_NUMERICAL',
 'VAR_ORDERED',
 '__doc__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__']

If you have installed an older version of OpenCV, the ml module might not be present. For example, the $k$-nearest neighbor algorithm (which we will talk about in Chapter 3, First Steps in Supervised Learning) used to be called cv2.KNearest but is now called cv2.ml.KNearest_create.

In order to avoid confusion throughout the book, I therefore recommend using at least OpenCV 3.1.