/ ai

Installing OpenCV on Raspberry Pi 3 B

September 5 2018 update: simpler, better process for OpenCV 3.4.3.

See new version of this guide:

https://www.alatortsev.com/2018/09/05/installing-opencv-3-4-3-on-raspberry-pi-3-b/

I am using the B version, purchased on Amazon, with the following specs:

  • 1.2GHz 64-bit quad-core ARMv8 CPU, 1 GB RAM
  • 802.11n Wireless LAN, 10/100Mbps LAN Speed
  • Bluetooth 4.1, Bluetooth Low Energy
  • 4 USB ports, 40 GPIO pins, Full HDMI port, Combined 3.5mm audio jack and composite video
  • Camera interface (CSI),Display interface (DSI), Micro SD card slot (now push-pull rather than push-push), VideoCore IV 3D graphics core

There is a newer version ("B+") there now and it should work the same way, but some steps (such as compiling OpenCV, which took almost 2 hours on my device) should be faster.

Also, as expected, compiling OpenCV made the fanless CPU overheat 30 min into the process - so I had to place a powerful fan next to it, until I receive a case with proper cooling.

Step 1: make sure you have the latest version of OS

Current OS version is Raspbian Stretch (April 2018). You can either do a clean install from SD (follow the instructions listed here), or upgrade your existing version.

To upgrade, open (as sudo) the files /etc/apt/sources.list and /etc/apt/sources.list.d/raspi.list in your favorite editor, and change all occurences of your current distro name (e.g. "jessie") to "stretch". Then, open a terminal and run the update:

sudo apt-get update
sudo apt-get -y dist-upgrade

Step 2: configure SSH and utilities

Make sure SSH is enabled. Change the default password, too!

Some of my favorite utilities on Linux are screen (to keep processes running if your terminal session is dropped) and htop (performance monitoring) - these may already be pre-installed:

sudo apt-get install screen
sudo apt-get install htop

Step 3: free up 1GB+ by ditching Wolfram and Libreoffice

It's unlikely that you will need these two packages on your computer vision box, so:

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

Step 4: install dependencies

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 libatlas-base-dev gfortran

Step 5: install Python 2.7 & 3

We need this in order to enable Python bindings in Open CV:

In OpenCV, all algorithms are implemented in C++. But these algorithms can be used from different languages like Python, Java etc. This is made possible by the bindings generators. These generators create a bridge between C++ and Python which enables users to call C++ functions from Python. To get a complete picture of what is happening in background, a good knowledge of Python/C API is required. A simple example on extending C++ functions to Python can be found in official Python documentation[1]. So extending all functions in OpenCV to Python by writing their wrapper functions manually is a time-consuming task. So OpenCV does it in a more intelligent way. OpenCV generates these wrapper functions automatically from the C++ headers using some Python scripts which are located in modules/python/src2

sudo apt-get install python2.7-dev 
sudo apt-get install python3-dev

Step 6: get the latest OpenCV source code

I am using version 3.4.1 of OpenCV. You can check the Releases section of the official site (or Github) to see what the current build is. If your desired version is different, update the commands and paths below accordingly.

Download and unzip OpenCV 3.4.1 and its experimental modules (those are stored in the opencv_contrib repository):

wget -O opencv.zip https://github.com/opencv/opencv/archive/3.4.1.zip

wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/3.4.1.zip

unzip opencv.zip

unzip opencv_contrib.zip

Step 7: install pip and virtualenv

These are the lowest-level tools for managing Python packages.

Get pip first:

wget -O get-pip.py https://bootstrap.pypa.io/get-pip.py 
sudo python get-pip.py
sudo python3 get-pip.py

Source: https://pip.pypa.io/en/stable/installing/

Then, install virtual environments:

sudo pip install virtualenv virtualenvwrapper

Modify your ~/.profile file to include the following lines:

export WORKONHOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source /usr/local/bin/virtualenvwrapper.sh

This is what my file looks like:

# ~/.profile: executed by the command interpreter for login shells.
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.
# see /usr/share/doc/bash/examples/startup-files for examples.
# the files are located in the bash-doc package.

# the default umask is set in /etc/profile; for setting the umask
# for ssh logins, install and configure the libpam-umask package.
#umask 022

# if running bash
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
        . "$HOME/.bashrc"
    fi
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

# virtualenv and virtualenvwrapper settings
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source /usr/local/bin/virtualenvwrapper.sh

... activate the changes:

source ~/.profile

Step 8: create a virtual environment

mkvirtualenv cv -p python3

... or, if you want to use Python 2.7 instead of Python 3:

mkvirtualenv cv -p python2

These are the basic commands for working with virtualenvwarapper:

mkvirtualenv virtualenv_name # create virtualenv
workon virtualenv_name # activate/switch to a virtualenv
deactivate virtualenv_name # deactivate virtualenv

In our case, we can activate a virtualenv called "cv":

pi@raspberrypi:~ $ workon cv
(cv) pi@raspberrypi:~ $ 

Step 9: install Numpy, Scipy

Now that you are inside your virtual environment (as evidenced by the "(cv)" prefix in your terminal window), let's install some additional packages for data analysis - numpy and scipy:

sudo pip install numpy scipy

Step 10: finally, install OpenCV

Note: this will take a long, long, long time. Took almost 2 hours on my device. Also, your Raspberry Pi will overheat without proper cooling.

Again, I am using version 3.4.1 of OpenCV. If you aren't - update your paths accordingly:

cd ~/opencv-3.4.1/
mkdir build
cd build

cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.4.1/modules \
    -D BUILD_EXAMPLES=ON ..

Make sure cmake finishes without errors.

Now, get yourself a glass of beer, and prepare for the final step - compiling. To speed things up, temporarily increase the swap file size in your /etc/dphys-swapfile by changing CONF_SWAPSIZE from 100 to 1024:

# 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
#CONF_SWAPSIZE=100
CONF_SWAPSIZE=1024

To avoid rebooting in order for these changes to take effect, simply restart the swap service:

sudo /etc/init.d/dphys-swapfile restart

There's a detailed guide on how to compile OpenCV with packages here:

https://github.com/opencv/opencv_contrib

What I did (using all 4 CPU cores):

make -j4

Once OpenCV compiles successfully, continue the installation:

sudo make install
sudo ldconfig
sudo apt-get update

... then reboot the system - and you should be good to go!

One more thing:

Test the installation:

$ python3
Python 3.5.3 (default, Jan 19 2017, 14:11:04) 
[GCC 6.3.0 20170124] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'3.4.1'
>>> 

If you are getting an error (ImportError: No module named 'cv2'), the library may be named incorrectly:

(cv) pi@raspberrypi:$ ls -l /usr/local/lib/python3.5/site-packages/
total 4500
-rw-r--r-- 1 root staff 4604912 Apr 27 14:41 cv2.cpython-35m-arm-linux-gnueabihf.so

Fix it by renaming the library file to "cv2.so":

cd /usr/local/lib/python3.5/site-packages/
sudo mv cv2.cpython-35m-arm-linux-gnueabihf.so cv2.so