Building OpenCV 3.4 on Raspberry Pi

I’ve read many tutorials about building and installing OpenCV on a Raspberry Pi but they either did not work or were outdated. Hence, I decided to write down all steps required to build and install OpenCV 3.4.

 
# Update your system
sudo rpi-update
sudo apt-get update
sudo apt-get upgrade
 
# Change swap size
sudo nano /etc/dphys-swapfile
# Change this... CONF_SWAPSIZE=100 to this
CONF_SWAPSIZE=1024
 
# Restart service
sudo /etc/init.d/dphys-swapfile stop
sudo /etc/init.d/dphys-swapfile start
 
# Install packages
sudo apt-get install build-essential cmake cmake-curses-gui pkg-config
sudo apt-get install libatlas-base-dev gfortran
sudo apt-get install \
  libjpeg-dev \
  libtiff5-dev \
  libjasper-dev \
  libpng12-dev \
  libavcodec-dev \
  libavformat-dev \
  libswscale-dev \
  libeigen3-dev \
  libxvidcore-dev \
  libx264-dev \
  libgtk2.0-dev
 
sudo apt-get -y install libv4l-dev v4l-utils
 
sudo apt-get install python2.7-dev
sudo apt-get install python3-dev
 
pip install numpy
pip3 install numpy
 
# Install OpenCV
wget https://github.com/opencv/opencv/archive/3.4.0.zip -O opencv.zip
wget https://github.com/opencv/opencv_contrib/archive/3.4.0.zip -O opencv_contrib.zip
 
unzip opencv.zip
unzip opencv_contrib.zip
 
cd opencv-3.4.0
mkdir build
cd build
 
sudo cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D BUILD_WITH_DEBUG_INFO=OFF \
    -D BUILD_DOCS=OFF \
    -D BUILD_EXAMPLES=OFF \
    -D BUILD_TESTS=OFF \
    -D BUILD_opencv_ts=OFF \
    -D BUILD_PERF_TESTS=OFF \
    -D INSTALL_C_EXAMPLES=OFF \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-3.4.0/modules \
    -D ENABLE_NEON=ON \
    -D WITH_LIBV4L=ON \
        ..
 
sudo make -j3
sudo make install
sudo ldconfig
 
# Fix library file name
cd /usr/local/lib/python3.5/dist-packages/
sudo mv cv2.cpython-35m.so cv2.so

Cross compiling OpenCV for ARM from Ubuntu

Similar to the compilation of dlib for ARM on Ubuntu (see http://www.jofre.de/?p=1494) I’d like to provide a short guilde on how to compile OpenCV for ARM on Ubuntu.

First, install all required packages:
sudo apt-get install build-essential git cmake pkg-config libjpeg8-dev libtiff5-dev libjasper-dev libpng12-dev libavcodec-dev libavformat-dev libswscale-dev libv4l-dev libgtk2.0-dev libatlas-base-dev
gfortran

Download/clone OpenCV from github

Build OpenCV
mkdir build
cd build
cmake -DSOFTFP=ON -DCMAKE_TOOLCHAIN_FILE=/home/user1/opencv/platforms/linux/arm-gnueabi.toolchain.cmake ..

make