Top Ad unit 728 × 90


Install OpenCV on Raspberry PI





Install OpenCV 3.2 Python/C++ on Raspberry PI

Raspberry PI is a wonderful system and OpenCV is an outstanding library for computer vision. Here is our how to install and configure OpenCV 3.2.0 for Python/C++ on a Raspberry PI 2 with Raspbian Jessie. On the Net there are many references on this subject, most of them have some missed point or reference to old versions.
To use latest version of OpenCV with Python you need to build OpenCV from source using CMake. This operation is easy but many steps are required. Here is shown OpenCV 3.2.0 but information are still valid for 3.1.0.

Remove default (old) OpenCV

Raspbian comes with OpenCV ver. 2.4.9. Even if this version is quite outdated users could use it to do some practice. Going on with Computer Vision they would have latest version of the library.
This is right time to remove old libraries with:
sudo apt-get remove libopencv*
sudo apt-get autoremove

Do you have enough space ?

In this how-to we are going to download and build OpenCV 3.2.0 from scratch. About 2GB of temporary disk space is required to build OpenCV (only for Release version). It's common case that you don't have enough space left on your Raspberry PI... check it with:
df -h

Filesystem      Size  Used Avail Use% Mounted on
/dev/root       6.1G  5.1G  673M  89% /
devtmpfs        427M     0  427M   0% /dev
...
In this case only 673MB are available !
A simple solution is to use some external USB disk or memory where can to download and build OpenCV. After this you can remove (or delete) your external storage.
A Linux file system like ext2 is required because build process uses Linux symbolic link. You can't use some USB stick formatted as FAT or NTFS otherwise, at compile time, you will receive the obscure error:
CMake Error: cmake_symlink_library: System Error: Operation not permitted
If you have enough left space on your Raspberry PI or do you have some external memory formatted as Linux filesystem you can skip the next paragraph.

Formatting your USB memory as Linux Partition

WARNING!!!!! THE OPERATIONS DESCRIBED IN THIS PARAGRAPH WILL DESTROY ALL DATA PRESENT ON YOUR USB MEMORY. In addiction, to use the memory under MS Windows you will have to repartition as Windows and reformat it as vFAT or NTFS
  1. Plug some USB memory, minimum 2GB, into your Raspberry PI and check for the device name, typical name are /dev/sda1 or similar, use lsblk to list block devices on your Raspberry PI:
    lsblk
    
    NAME        MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
    sda           8:0    1 14.6G  0 disk
      sda1        8:1    1 14.6G  0 part
    mmcblk0     179:0    0  7.4G  0 disk
      mmcblk0p1 179:1    0    1G  0 part
      mmcblk0p2 179:2    0    1K  0 part
      mmcblk0p3 179:3    0   32M  0 part
      mmcblk0p5 179:5    0   60M  0 part /boot
      mmcblk0p6 179:6    0  6.2G  0 part /
    
  2. Make sure that the memory is not mounted. In case unmount it with
    sudo umonut /dev/your-dev-name
  3. Create a Linux partition using
    sudo fdisk /dev/your-dev-name
    • Print list of partitions using command p
    • Delete all existing partition using command d for each partitions
    • Create a new partition using command c
    • Print list of partition using command p
    • Ensure that the partition type is Linux. In case change it using command t
    • Save changes and exit with command w
  4. Format the new partition using:
    sudo mkfs -t ext2 /dev/your-dev-name
  5. Create a mount point and mount the memory:
    mkdir ~/usbmem
    sudo mount /dev/your-dev-name ~/usbmem
    
After this we'll use /home/pi/usbmem as working directory for all next steps.

Installing prerequisites

Update your system

sudo apt-get update
sudo apt-get upgrade
sudo rpi-update
sudo reboot
This would requires long time if your system isn't updated. At the end reboot your system.

Install the devel tools

sudo apt-get install build-essential cmake cmake-curses-gui pkg-config

Install the required libraries

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

Video4Linux

Python manages Raspberry's camera by the way of  picamera module. You can use this module also in OpenCV but you have to grab images to numpy.array then map the array to OpenCV Mat.
To use the standard grabbing loop cv2.VideoCapture(0)  with raspicam the Video4Linux driver is needed.
  1. Check prerequisites (with sudo raspi-config):
    1. Enable the camera
    2. Set large memory for gpu_mem (In Advance Options > Memmory Split set 128 min)
  2. Install v4l library from repository:
    sudo apt-get -y install libv4l-dev v4l-utils
  3. Enable the kernel module:
    sudo modprobe bcm2835-v4l2
  4. Test the module with:
    v4l2-ctl --list-devices
    You should receive something like this:
    mmal service 16.1 (platform:bcm2835-v4l2):
             /dev/video0
  5. Test: try to grab a single frame and check for the file  ~/test.jpg
    v4l2-ctl --set-fmt-video=width=800,height=600,pixelformat=3
    v4l2-ctl --stream-mmap=3 --stream-count=1 --stream-to=~/test.jpg
  6. Info: check all available controls like brightness, contrast,.. with:
    v4l2-ctl --list-ctrls
If all it works well add the module name bcm2835-v4l2 to the list of modules loaded at boot time in /etc/modules-load.d/modules.conf

Additional libraries

sudo apt-get install libatlas-base-dev gfortran

Setup Python

On Raspbian Jessie both Python 2.7 and Python 3 are available. Here we are installing OpenCV 3.2.0 for both Python versions.
Is a Python best practice to use a virtualenv to isolate packages into dedicated environment. Adrian Rosebrock on pyimagesearch has very nice tutorial on how to do this (check the link in the Credit paragraph).
Because our Raspberry PI is dedicated to OpenCV we don't use virtualenv here.

Install python-dev & numpy

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

Lets go with OpenCV

Here we are going to download, configure, build and install OpenCV.

Download OpenCV

Remember that if you don't have at least 2GB on your root partition you have to use some external memory (Linux partition). Here we are using an USB memory mounted in /home/pi/usbmem.
sudo mount /dev/your-dev-name /home/pi/usbmem
mkdir /home/pi/usbmem/opencv
cd  /home/pi/usbmem/opencv
wget https://github.com/opencv/opencv/archive/3.2.0.zip -O opencv_source.zip
wget https://github.com/opencv/opencv_contrib/archive/3.2.0.zip -O opencv_contrib.zip
We re going to install opencv_contrib even if this repo contains new modules quite often do not have stable API, and they are not well-tested.

Unzip the files

cd /home/pi/usbmem/opencv
unzip opencv_source.zip
unzip opencv_contrib.zip

Build & Install OpenCV

To build and install OpenCV for C++, Python2 and Python3 we need to use CMake. OpenCV has a lot of options you can choose at compile time. You can select options using command line switch and/or using ccmake (that is CMake text based user interface).

Create the working directory:

cd /home/pi/usbmem/opencv/opencv-3.2.0
mkdir build
cd build

Start to configure your build using command line switch

Here is our default configuration. We don't want a Debug version neither Tests. We suggest to enable NEON optimization for ARM Cortex to increase (a bit) OpenCV performance.
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=ON \
 -D INSTALL_PYTHON_EXAMPLES=ON \
 -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-3.2.0/modules \
 -D ENABLE_NEON=ON \
 -D WITH_LIBV4L=ON \
        ../
CMake should start to build your configuration, after a couple of minutes you should see:
.....
-- Configuring done
-- Generating done
-- Build files have been written to: /home/pi/usbmem/opencv/opencv-3.2.0/build
If you can't see Generating done then some issues have been occurred. Read error messages and the error log file to investigate.
If generating done and if you like our default configuration you can skip the next paragraph.

Review/modify the configuration using CMake TextGUI

 You can change some command line switch from above or you can use ccmake to configure all available options
$ ccmake ../
                                       Page  1 of ..
 ANT_EXECUTABLE                   ANT_EXECUTABLE-NOTFOUND
 BUILD_CUDA_STUBS                 OFF
 BUILD_DOCS                       OFF
 BUILD_EXAMPLES                   OFF
 BUILD_JASPER                     ON
 BUILD_JPEG                       ON
 BUILD_LIBPROTOBUF_FROM_SOURCES   OFF
 BUILD_OPENEXR                    OFF
 ... more options here ....

Press [enter] to edit option
Press [c] to configure
Press [h] for help           Press [q] to quit without generating
Press [t] to toggle advanced mode (Currently Off)
Scroll the list and change options you want.
When you have done press c to configure. If no errors occurs press g to generate the makefile.

Build OpenCV

It's time to go ! (use -jn to spawn build on n thread)
make -j4
Compilation process takes very long time... In case of error it will stop otherwise, after about 2 hours (on Rasperry 2) you will see:
[100%] Built target ...

Install OpenCV

Just a quick step with:
sudo make install
sudo ldconfig
Congratulations your Raspberry PI is ready for the Computer Vision ! By default files will be installed in:
/usr/local/lib/libcv*
/usr/local/lib/python2.7/dist-packages/cv*
/usr/local/lib/python3.4/dist-packages/cv*
/usr/local/include/opencv2/
/usr/local/bin/opencv_*
/usr/local/share/OpenCV/

Test the installation

Test with Python 2 or Python 3

From terminal window run python, import cv2 and print its version:
$ python3
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> print (cv2.__version__)
3.2.0
>>>
Test live grabbing... from your graphic interface run idle3 (or idle2), create a new file ~/ocv-tests/SimpleGrab.py
 
import numpy as np
import cv2
 
cap = cv2.VideoCapture(0)
 
if cap.isOpened() == False:
    print('Unable to open the camera')
else:
    print('Start grabbing, press a key on Live window to terminate')
    cv2.namedWindow('Live');
    cap.set(cv2.CAP_PROP_FRAME_WIDTH,320)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT,240)
    while( cap.isOpened() ):
        ret,frame = cap.read()
        if ret==False:
            print('Unable to grab from the camera')
            break
 
        cv2.imshow('Live',frame)
        #cv2.waitKey(0);
        key = cv2.waitKey(5)
        if key==255: key=-1 #Solve bug in 3.2.0
        if key >= 0:
            break
    print('Closing the camera')
 
cap.release()
cv2.destroyAllWindows()
print('bye bye!')
quit()
Run it with F5 and... the Live window should appears on your desktop! Check other OpenCV samples in /usr/local/share/OpenCV/samples/python

Test with C++

Test live grabbing... from your graphic interface create a new file ~/ocv-tests/SimpleGrab.cpp
 
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
 
using namespace cv;
using namespace std;
 
int main(int argc,char ** argv)
{
  VideoCapture cap(0);
  if (!cap.isOpened()) {
    cerr << "ERROR: Unable to open the camera" << endl;
    return 0;
  }
 
  Mat frame;
  cout << "Start grabbing, press a key on Live window to terminate" << endl;
  while(1) {
    cap >> frame;
    if (frame.empty()) {
        cerr << "ERROR: Unable to grab from the camera" << endl;
        break;
    }
    imshow("Live",frame);
    int key = cv::waitKey(5);
    key = (key==255) ? -1 : key; //#Solve bug in 3.2.0
    if (key>=0)
      break;
  }
 
  cout << "Closing the camera" << endl;
  cap.release();
  destroyAllWindows();
  cout << "bye!" <<endl;
  return 0;
}
Build it with:
g++ $(pkg-config --libs --cflags opencv) -o SimpleGrab SimpleGrab.cpp
Run it with ./SimpleGrab ...the Live window should appears on your desktop! Check other OpenCV samples in /usr/local/share/OpenCV/samples/
Install OpenCV on Raspberry PI Reviewed by Jacky Le on July 12, 2017 Rating: 5

No comments:

All Rights Reserved by JackyLe © 2018 © 2017
Edit bởi: Jacky Le | Youtube Channel: JACKY LE

Send email form

Name

Email *

Message *

Powered by Blogger.