loading...
  1. Install OpenCV 3.3 and Python(2.7 & 3.5) bindings on Ubuntu 16.04

Install OpenCV 3.3 and Python(2.7 & 3.5) bindings on Ubuntu 16.04

Hello,

In this post, we are going to cover, how to install OpenCV 3.3 and Python 2.7 or 3.5 bindings on latest and greatest Ubuntu 16.04.

For windows users, please follow this blog post Install OpenCV 3.3 on Windows with Visual Studio 2015

Even if you already have installed Python on Ubuntu, you can still follow this guide to configure OpenCV on Ubuntu.

Install OpenCV and Python on Ubuntu 16.04

It is important to note that Ubuntu 16.04 actually ships out-of-the-box with both Python 2.7 and Python 3.5 installed. The actual versions are:

  • Python 2.7.12 (used by default when you type python in your terminal).
  • Python 3.5.2 (can be accessed via the python3 command).

In either case, this tutorial will support both Python 2.7 and Python 3. I have tried my best to highlighted the steps that will require you to make a decision regarding which version of Python you would like to use. Make sure you are consistent with your decision, otherwise you will inevitably run into compile, linking, and import errors and a huge time loss.

Regarding which Python version is the best and which one you should use…we can’t cover that in this post. If you have prior experience with any of them, use that otherwise python3 is the future. Long story short: the bindings will work just the same.

Enough talk, let’s get to work.

Step #1 :  Install OpenCV dependencies on Ubuntu 16.04

Launch your Ubuntu Terminal either using console session or using Putty and update the aptget package manager to refresh and upgrade and pre-installed packages/libraries:

1
2
3
#Install OpenCV with Python on Ubuntu 16.04
sudo apt-get update
sudo apt-get upgrade

Next, install developer tools:
The pkg-config package should already be installed on your system, but be sure to include it in the above apt-get command just in case.
The cmake program is used to automatically configure our OpenCV build.

1
2
#Install OpenCV with Python on Ubuntu 16.04
sudo apt-get install build-essential cmake pkg-config

Since, OpenCV is an image processing and computer vision library, therefore, OpenCV needs to be able to load various image file formats from disk such as JPEG, PNG, TIFF, etc. In order to load these images from disk, OpenCV actually depends upon other image I/O libraries which actually facilitate the loading and decoding process. We install the necessary ones below:

1
2
#Install OpenCV with Python on Ubuntu 16.04
sudo apt-get install libjpeg8-dev libtiff5-dev libjasper-dev libpng12-dev

Good Job, we now have the libraries to load the images from disk but since, we are most likely to use our webcam’s or external camera’s to taste the full flavor of opencv, we need to install additional packages to process video streams from cameras :

1
2
3
#Install OpenCV with Python on Ubuntu 16.04
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt-get install libxvidcore-dev libx264-dev

Default OpenCV setup comprises of very limited GUI tools. These assist us to display an image, track mouse events, mouse sliders/trackbars etc. highgui is the module that contains all these which relies on GTK library, which can be installed using the following command.

1
2
#Install OpenCV with Python on Ubuntu 16.04
sudo apt-get install libgtk-3-dev

Next, we install libraries that are used to optimize various functionalities inside OpenCV, such as matrix operations:

1
2
#Install OpenCV with Python on Ubuntu 16.04
sudo apt-get install libatlas-base-dev gfortran

Finally, to conclude Step #1, we’ll install Python development headers and libraries for both Python 2.7 and Python 3.5 (that way you have both):

1
2
#Install OpenCV with Python on Ubuntu 16.04
sudo apt-get install python2.7-dev python3.5-dev

Note: If you do not install the Python development headers and static library, you’ll run into issues during Step #4 where we run cmake to configure our build. If these headers are not installed, then the cmake command will be unable to automatically determine the proper values of the Python interpreter and Python libraries. In short, the output of this section will look “empty” and you will not be able to build the Python bindings. When you get to Step #4, take the time to compare your output of the command to mine.

Step #2: Download the OpenCV source code
At the time of this blog post, the most recent version of OpenCV is 3.3.0 , which we download as a .zip and unzip it using the following command:

1
2
3
4
#Install OpenCV with Python on Ubuntu 16.04
cd ~
wget -O opencv.zip https://github.com/Itseez/opencv/archive/3.3.0.zip
unzip opencv.zip

We also need the opencv_contrib repository as well:

1
2
3
#Install OpenCV with Python on Ubuntu 16.04
wget -O opencv_contrib.zip https://github.com/Itseez/opencv_contrib/archive/3.3.0.zip
unzip opencv_contrib.zip

Why download the contrib repo?
Because, we want the full blown install of OpenCV 3.3 to have access to special features as well such as SIFT and SURF. In OpenCV 2.4, SIFT and SURF were par of the default installation of OpenCV. However, with the release of OpenCV 3+, these packages have been moved to contrib.

Also, make sure that both opencv and opencv_contrib versions should be the same (in this case, 3.3.0 ). If the versions numbers do not matchup, you could very easily run into compile time errors (or worse, runtime errors that are near impossible to debug).

Step #3: Setup your Python 2.7 or Python 3 Bindings and Environment

Okay, so up till here, we have downloaded the required libraries for OpenCV to work and also downloaded OpenCV Source and contrib. Now, we are ready to configure our Python Development Environment for the build. First step is to install PIP which is a Python Package Manager:

1
2
3
4
#Install OpenCV with Python on Ubuntu 16.04
cd ~
wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py

Okay so before moving on, we need to talk a bit about Virtual Environments and how they can help you in segregating your environments.
Virtualenv is a tool to create isolated Python environments. Long story short, using these packages, you can solve the “Project A depends on version 1.x, but Project Z needs 4.x dilemma. A fantastic side effect of using Python virtual environments is that you can keep your system Python neat, tidy, and free from clutter. I am a fan of virtual environment and would recommend you to use it. We’ll use them by doing the following:

1
2
3
#Install OpenCV 3.3 with Python on Ubuntu 16.04
sudo pip install virtualenv virtualenvwrapper
sudo rm -rf ~/get-pip.py ~/.cache/pip

Once we have virtualenv and virtualenvwrapper installed, we need to update our ~/.bashrc file to include the following lines at the bottom of the file:

1
2
3
#Install OpenCV 3.3 with Python on Ubuntu 16.04
export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

The ~/.bashrc file is simply a shell script that Bash runs whenever you launch a new terminal window. You normally use this file to set various configurations. In this case, we are setting an environment variable called WORKON_HOME to point to the directory where our Python virtual environments live. We then load any necessary configurations from virtualenvwrapper.

1
2
3
4
#Install OpenCV 3.3 with Python on Ubuntu 16.04
echo -e "\n# virtualenv and virtualenvwrapper" >> ~/.bashrc
echo "export WORKON_HOME=$HOME/.virtualenvs" >> ~/.bashrc
echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.bashrc

After editing our ~/.bashrc file, we need to reload the changes:

1
2
#Install OpenCV 3.3 with Python on Ubuntu 16.04
source ~/.bashrc

Note: Calling source on .bashrc only has to be done once for our current shell session.
Anytime we open up a new terminal, the contents of .bashrc will be automatically executed (including our updates).

Now that we have installed virtualenv and virtualenvwrapper , the next step is to actually create the Python virtual environment — we do this using the mkvirtualenv command.

Here, you need to make your choice, would you like to choose Python 2.7 or Python 3? Your answer would define the next command

1
2
#Install OpenCV 3.3 with Python on Ubuntu 16.04
mkvirtualenv cv -p python2

Otherwise,

1
2
#Install OpenCV 3.3 with Python on Ubuntu 16.04
mkvirtualenv cv -p python3

Whichever command you use, the end result is that we have created a Python virtual environment named cv (short for “computer vision”). You can name it whatever you want(ai, vi, mi, myworld, myvision, yourvision etc. etc.)

You can verify that it works by simply running the below command:

1
2
#Install OpenCV 3.3 with Python on Ubuntu 16.04
workon cv

To validate that you are in the cv virtual environment, simply examine your command line — if you see the text (cv) preceding your prompt, then you are in the cv virtual environment:

 

Let’s install the great NumPy into your Python virtual environment

This the final step before we compile OpenCV. NumPy is a Python package used for numerical processing. Execute the following command:

1
2
#Install OpenCV 3.3 with Python on Ubuntu 16.04
pip install numpy

Step #4: Configuring and compiling OpenCV on Ubuntu 16.04

At this point, all of our necessary prerequisites have been installed — we are now ready to compile and OpenCV!

1
2
3
4
5
6
7
8
9
10
11
12
#Install OpenCV with Python on Ubuntu 16.04
workon cv
cd ~/opencv-3.3.0/
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D INSTALL_C_EXAMPLES=OFF \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.3.0/modules \
-D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python \
-D BUILD_EXAMPLES=ON ..

Note: If you are getting an error related to stdlib.h: No such file or directory during either the cmake or make phase of this tutorial you’ll also need to include the following option to CMake: -D ENABLE_PRECOMPILED_HEADERS=OFF . In this case I would suggest deleting your build directory, re-creating it, and then re-running CMake with the above option included. This will resolve the stdlib.h error.

Inside this directory we create a sub-directory named build and change into it. The build directory is where the actual compile is going to take place.

Finally, we execute cmake to configure our build.

Before we move on to the actual compilation of OpenCV, make sure you examine the output of CMake!

To do this, scroll down the section titled Python 2 and Python 3 .

If you are compiling OpenCV on Ubuntu 16.04 with Python 2.7 support, make sure the Python 2 section includes valid paths to the Interpreter , Libraries , numpy , and packages path . Your output should be similar to mine below:

Examining this output, you can see that:

The Interpreter points to the Python 2.7 binary in the cv virtual environment.
Libraries points to the Python 2.7 library (which we installed during the final step of Step #1).
The numpy value points to our NumPy installation in the cv virtual environment.
And finally, the packages path points to lib/python2.7/site-packages . When combined with the CMAKE_INSTALL_PREFIX , this means that after compiling OpenCV, we’ll find our cv2.so bindings in /usr/local/lib/python2.7/site-packages/ .
Similarly, if you’re compiling OpenCV 16.04 with Python 3 support, you’ll want to ensure your Python 3 section looks similar to mine below:

Again, notice how my Interpreter , Libraries , numpy  and packages path  have all been correctly set.

If you do not see the cv  virtual environments in these variable paths, it’s almost certainly because you are NOT in the cv  virtual environment prior to running CMake!

If that is indeed the case, simply access the cv  virtual environment by calling workon cv  and re-run the CMake command mentioned above.

Assuming your CMake command exited without any errors, you can now compile OpenCV:

1
2
#Install OpenCV with Python on Ubuntu 16.04
make -j8

The -j switch controls the number of processes to be used when compiling OpenCV — you’ll want to set this value to the number of processors/cores on your machine. In my case, I have a octa-core processor, so I set -j8 . Using multiple processes allows OpenCV to compile faster; however, there are times where race conditions are hit and the compile bombs out.

Below you can find a screenshot of a successful OpenCV 3.3 with Python compile on Ubuntu 16.04

Hurray,  Finally, The last step is to actually install OpenCV 3 on Ubuntu 16.04:

1
2
3
4
#Install OpenCV with Python on Ubuntu 16.04
cd ~
sudo make install
sudo ldconfig

Step #5: Finish your OpenCV install
Hold tight, you are almost there, just a few more steps and we are done with it…

For Python 2.7:
After running sudo make install , your Python 2.7 bindings for OpenCV 3 should now be located in /usr/local/lib/python-2.7/site-packages/ . You can verify this using the ls command:

1
2
3
4
#Install OpenCV with Python on Ubuntu 16.04
ls -l /usr/local/lib/python2.7/site-packages/
total 1972
-rw-r--r-- 1 root staff 2016608 Sep 15 09:11 cv2.so

Note: In some cases, you may find that OpenCV was installed in /usr/local/lib/python2.7/dist-packages rather than /usr/local/lib/python2.7/site-packages (note dist-packages versus site-packages ). If your cv2.so bindings are not in the site-packages directory, be sure to check dist-pakages .

The final step is to sym-link our OpenCV cv2.so bindings into our cv virtual environment for Python 2.7:

1
2
3
#Install OpenCV with Python on Ubuntu 16.04
cd ~/.virtualenvs/cv/lib/python2.7/site-packages/
ln -s /usr/local/lib/python2.7/site-packages/cv2.so cv2.so

For Python 3.5:
After running sudo make install , your OpenCV + Python 3 bindings should be located in /usr/local/lib/python3.5/site-packages/ . Again, you can verify this using the ls command:

1
2
3
4
#Install OpenCV with Python on Ubuntu 16.04
ls -l /usr/local/lib/python3.5/site-packages/
total 1972
-rw-r--r-- 1 root staff 2016816 Sep 13 17:24 cv2.cpython-35m-x86_64-linux-gnu.so

For python 3, the filename might not be cv2.so, so we need to change it and symlink it.

1
2
3
4
5
#Install OpenCV with Python on Ubuntu 16.04
cd /usr/local/lib/python3.5/site-packages/
sudo mv cv2.cpython-35m-x86_64-linux-gnu.so cv2.so
cd ~/.virtualenvs/cv/lib/python3.5/site-packages/
ln -s /usr/local/lib/python3.5/site-packages/cv2.so cv2.so

Step #6: Testing your OpenCV install
First of all, Congratulations, you now have OpenCV 3.3 installed on your Ubuntu 16.04 system!

To verify that your installation is working:

Open up a new terminal.
Execute the workon command to access the cv Python virtual environment.
Attempt to import the Python + OpenCV bindings.
Below are the steps on how to perform it:

1
2
3
4
5
6
7
8
9
10
#Install OpenCV with Python on Ubuntu 16.04
cd ~
workon cv
python
Python 3.5.2 (default, Jul 5 2016, 12:43:10)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
import cv2
cv2.__version__
'3.1.0'

That’s all for this post.
Before i sum-up, i would like to share my personal thanks message and lots of credits to my guy Adrian for this wonderful tutorial that he shared on his blog.

Swap colors in an image using OpenCV and Python
(Step by Step) Install OpenCV 3.3 with Visual Studio 2015 on Windows 10 x64 (2017 DIY)




5 thoughts on “Install OpenCV 3.3 and Python(2.7 & 3.5) bindings on Ubuntu 16.04”

  1. Xenoshell says:

    echo -e “\n# virtualenv and virtualenvwrapper” >> ~/.bashrc
    echo “export WORKON_HOME=$HOME/.virtualenvs” >> ~/.bashrc
    echo “source /usr/local/bin/virtualenvwrapper.sh” >> ~/.bashrc

    This command doesnt seem to work for me. Im on ubuntu mate 16.2.
    The error is: bash: syntax error near unexpected token `;&’
    Any help?

    1. Xenoshell says:

      oh its probably 16.04.2 but thats not really the important part. Cant edit my comment

  2. Editor says:

    Try these 3 commands instead:

    echo -e “\n# virtualenv and virtualenvwrapper” >> ~/.bashrc
    echo “export WORKON_HOME=$HOME/.virtualenvs” >> ~/.bashrc
    echo “source /usr/local/bin/virtualenvwrapper.sh” >> ~/.bashrc

    make sure if you copy them, the quotes are linux style(you might want to backspace them and then re-enter the quotes if the copy paste doesn’t work)

  3. Dayananda Herurkar says:

    When I run source ~/.bashrc command I get below error

    /home/dayananda/miniconda2/bin/python: No module named virtualenvwrapper
    virtualenvwrapper.sh: There was a problem running the initialization hooks.

    If Python could not import the module virtualenvwrapper.hook_loader,
    check that virtualenvwrapper has been installed for
    VIRTUALENVWRAPPER_PYTHON=/home/dayananda/miniconda2/bin/python and that PATH is
    set properly.

    Please let me know what is the issue here.

    Thanks

    1. Editor says:

      You need to install them under python 2.7 or 3.5 by specifying the path to correct version of pip to be used.
      Or If you have modified your virtualenvwrapper to point to python3::
      export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3

      then make sure you install the virtualenv and virtualenvwrapper using:
      sudo /usr/local/bin/pip3 install virtualenv virtualenvwrapper

Leave a Reply

Your email address will not be published. Required fields are marked *

Welcome to OpenCV World !! Come as a Guest, stay as a Family