was successfully added to your cart.

Install OpenCV 3 on Raspberry Pi Raspbian

By November 5, 2017Raspberry Pi

Let’s release some more space on your SD card first.

$ sudo apt-get purge wolfram-engine
$ sudo apt-get purge libreoffice*
$ sudo apt-get clean
$ sudo apt-get autoremove

Almost 700MB space will be cleaned up when the unnecessary applications purged.

$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo rpi-update
$ sudo reboot

Install dependencies

$ sudo apt-get update && sudo apt-get upgrade
$ sudo apt-get install build-essential cmake pkg-config
$ sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev
$ sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
$ sudo apt-get install libxvidcore-dev libx264-dev
$ sudo apt-get install libgtk2.0-dev libgtk-3-dev
$ sudo apt-get install libcanberra-gtk*
$ sudo apt-get install libatlas-base-dev gfortran
$ sudo apt-get install python2.7-dev python3-dev



Within the Python virtual environment, please do remember there is no sudo before cmake command. The cmake result should be like the one down below if you are using Python 3.5. Pay attention to path value of numpy.

Before you start the compile I would suggest increasing your swap space. This will enable you to compile OpenCV with all four cores of the Raspberry Pi without the compile hanging due to memory exhausting.

Open up your /etc/dphys-swapfile file and then edit the CONF_SWAPSIZE variable:

# set size to absolute value, leaving empty (default) then uses computed value
#   you most likely don't want this, unless you have an special disk situation

If you do not perform this step it’s very likely that your Pi will hang.

From there, restart the swap service:

$ sudo /etc/init.d/dphys-swapfile stop
$ sudo /etc/init.d/dphys-swapfile start
$ make -j4
$ sudo make install
$ sudo ldconfig

Don’t forget to go back to your /etc/dphys-swapfile file and:

Restart the swap service.

If you compiled OpenCV for Python 3, you need to issue the following commands to sym-link the cv2.so bindings into your cv virtual environment:

$ cd /usr/local/lib/python3.5/site-packages/
$ sudo mv cv2.cpython-35m-arm-linux-gnueabihf.so cv2.so
$ cd ~/.virtualenvs/cv/lib/python3.5/site-packages/
$ ln -s /usr/local/lib/python3.5/site-packages/cv2.so cv2.so

Keep in mind that the exact paths will need to be updated depending if you are using Python 3.4, Python 3.5, Python 3.6, etc.
If you instead compiled OpenCV for Python 2.7, you can use these commands to sym-link your cv2.so file into the cv virtual environment:

$ cd ~/.virtualenvs/cv/lib/python2.7/site-packages/
$ ln -s /usr/local/lib/python2.7/site-packages/cv2.so cv2.so

Testing your optimized OpenCV + Raspberry Pi install

$ cd ~/.virtualenvs/cv/bin/
$ source activate
$ python
>>> import cv2
>>> cv2.__version__