There are a handful of answers strewn across the internet about installing OpenCV’s Python bindings, but none of them seem to apply to installing them in a virtualenv in Linux. In the interest of collecting all that information in one place, here’s what I did to get it running. I’m using:
Ubuntu 14.04 64 bit
This will install OpenCV, the Python bindings, and Numpy system-wide, but afterward you will be able to use them inside a virtualenv. This assumes you have pip, virtualenv, and virtualenvwrapper installed and properly configured. If you aren’t familiar with these, Googling yields many resources, for example this tutorial.
First, install OpenCV’s dependencies, per the installation instructions. (Some of these were pre-installed on my system)
$ sudo apt-get install build-essential cmake libgtk2.0-dev pkg-config python-dev libavcodec-dev libavformat-dev libswscale-dev
The next part had me tripped up for a little bit. OpenCV doesn’t play particularly well with virtualenvs, so numpy needs to be installed on the system Python:
$ sudo pip install numpy
After that, continue to build OpenCV per the instructions. Download the source (I’m using version 18.104.22.168, from here) and unzip it in the directory of your choice.
$ unzip opencv-2.4.9.zip $ cd opencv-2.4.9 $ mkdir build $ cd build
Configure the make files using cmake. There is a flag required for the Python bindings that I couldn’t find in the official documentation, only in StackOverflow
questions: BUILD_NEW_PYTHON_SUPPORT. Also note the two trailing periods.
$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_NEW_PYTHON_SUPPORT=ON ..
This will output a lot of text, but if you scroll up you should find a section referring to Python. It will refer to the system Python binary. This is fine. We will set up our virtualenv later.
After the build is configured, time to make the project. This will take a few minutes to run.
$ make $ sudo make install
After the build completes, you need to set up your virutalenv if you haven’t already. Numpy also needs to be installed in the virtualenv.
$ mkvirutalenv opencv [...] (opencv) $ pip install numpy
Now that our virtualenv is ready to go, we just need to copy the OpenCV binary into the virtualenv’s site-packages directory.
(opencv) $ cd lib (opencv) $ cp cv2.so ~/.virtualenvs/opencv/lib/python2.7/site-packages
Everything should be good to go:
(opencv) $ python >>> import cv2 >>>
If you get [/bash]ImportError: no module named cv2[/bash], double check you had the BUILD_NEW_PYTHON_SUPPORT flag set, and that numpy is installed for the system Python. If you get the error message
ImportError: numpy.core.multiarray failed to import
you need to install numpy in your virtualenv. From inside the virtualenv,
(opencv) $ pip install numpy
should fix that. I believe that should do the trick. Good luck with your computer vision!