It's a good idea to double-check our installation. While our terminal is still open, we start IPython, which is an interactive shell to run Python commands:
$ ipython
Next, make sure that you are running (at least) Python 3.6 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.6.0 | packaged by conda-forge | (default, Feb 9 2017, 14:36:55) [GCC 4.8.2 20140120 (Red Hat 4.8.2-15)]
Now try to import OpenCV as follows:
In [2]: import cv2
You should get no error messages. Then, try to find out the version number like so:
In [3]: cv2.__version__
Out[3]: '4.0.0'
Make sure that OpenCV's version number reads at 4.0.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 the 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 this:
$ jupyter notebook
This will automatically open a browser window, showing a list of files in the current directory. Click on the OpenCV-ML folder, then on the notebooks folder, and voila! Here you will find all the code for this book, ready to be explored:
The notebooks are arranged by chapter and section. For the most part, they contain only the relevant code, but no additional information or explanations. These are reserved for those who support our effort by buying this book—so thank you!
Simply click on a notebook of your choice, such as 01.00-A-Taste-of-Machine-Learning.ipynb, and you will be able to run the code yourself by selecting Kernel | Restart | Run All:
There are a few handy keyboard shortcuts for navigating Jupyter Notebooks. However, the only ones that you need to know about right now are the following:
- Click in a cell (note the highlighted region in the preceding screenshot—that's referred to as a cell) in order to edit it
- While the cell is selected, hit Ctrl + Enter to execute the code in it
- Alternatively, hit Shift + Enter to execute a cell and select the cell below it
- Hit Esc to exit write mode, then hit A to insert a cell above the currently selected one and B to insert a cell below
However, I strongly encourage you to follow along with the book by actually typing out the commands yourself, preferably in an IPython shell or an empty Jupyter Notebook. There is no better way to learn how to code than by getting your hands dirty. Even better if you make mistakes—we have all been there. At the end of the day, it's all about learning by doing!