Monday, February 9, 2015

Python (virtualenv), installing OpenCV, Ubuntu 14.04

I recently wanted to install OpenCV with Python 3.4 bindings on my Ubuntu 14.04 system.

I ran into several errors: Can not find Python.h even though python3-dev was installed. And, prior to that, cmake was not picking up the python libraries path.

Through some extensive googling I discovered that cmake 2.8.10 has a known bug with correctly finding the python includes directory. Refer to this bug report.

This issue was resolved by updating Ubuntu's version of cmake (which was ancient) and judicious use of opencv compilation flags. Specifically, I installed a newer cmake with:

wget http://www.cmake.org/files/v3.1/cmake-3.1.2.tar.gz 
tar -zxvf cmake-3.1.2.tar.gz 
cd cmake-3.1.2 mkdir _build 
cd _build 
cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr
make 
sudo make install 
sudo ldconfig 

and used the following opencv flags to build opencv for my python3 virtual env:

cmake -DBUILD_TESTS=OFF -DBUILD_PERF_TESTS=OFF -DBUILD_opencv_python2=OFF -DBUILD_opencv_python3=ON -DPYTHON3_EXECUTABLE=/home/kwame/py34/bin/python -DPYTHON_INCLUDE_DIRS=/usr/include/python3.4m -DPYTHON3_LIBRARY=/home/kwame/py34/lib/python3.4/config-3.4m-x86_64-linux-gnu/libpython3.4m.so -DPYTHON3_NUMPY_INCLUDE_DIRS=build/numpy-1.9.1/numpy/core/include/ -DPYTHON3_PACKAGES_PATH=/home/kwame/py34/lib/python3.4/site-packages -DWITH_TBB=ON .. 
make -j8 
sudo make install 
sudo ldconfig

I leave off the tests because they are statically linked and bloat the library sizes. I only build opencv for python 3.

The opencv installation was verified as working within Python3 by the following:

ipython
import cv