Italiano - English

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/

Credits

Here some useful link on same subject

Vote this page:

37 Comments:

#1 Sent by Dottor M 13-07-2016

If I try to use BUILD_EXAMPLES=ON I get an error for an invalid "remove" on the CMakelist of the gpu examples.

I'm now trying to go with BUILD_EXAMPLES=OFF (which configure) but how I can resolve the problem ? I need examples (even if without gpu part)...

#2 Sent by snot 30-09-2016

Works like a charm !
Thanks a lot it's very rare to have a tuto with no pb at all !

#3 Sent by Peter 27-11-2016

Wonderful. No hickups. Worked directly. Compile time on Pi 3, 45 minutes.
Question: Why Python? C and its derivates covers it all.
Regards
Peter

#4 Sent by thanks 07-12-2016

Thanks very very thanks by admin
Raspbery pi3 raspbian whit pixel compile time 45 minuts :)
very easy and comfort installer library :) :)

#5 Sent by Naegsh 12-12-2016

Upto
sudo make install
sudo ldconfig
all steps are successful

But for $python3
>>import cv2
it shows illegal instruction

Please provide me solution

#6 Sent by Mert Kahyaoğlu 19-12-2016

Thank you for step by step explantion.

All process was working well.

#7 Sent by Gbenga 30-12-2016

the installation was successfully done. i try to run the c++ code example, but i did not see any live window.\r\nwhat can i do?\r\n

#8 Sent by PkLab 04-01-2017

@Gbenga Are you using any console/ssh connection or you run the program from xterm within your GUI desktop session ? BTW the live window is shown on X win/session. In case of ssh connection you have to enable and configure X11 forwarding on your raspberry and your client.

#9 Sent by K13 11-01-2017

Thanks pkLab..
I am using Raspbian jessie lite

successful upto make install

But for $python3
>>import cv2
it shows illegal instruction

I observed that numpy is not installed for Python3
Please give me solution

#10 Sent by PkLab 31-01-2017

@K13 Solution is in the article:
Code:
sudo apt-get install python3-dev python3-numpy

#11 Sent by Yashvardhan Biyani 06-02-2017

My CMake is giving error while building. \"Configuring incomplete. Errors occurred!!!\". I did everything as it is said. I can\'t figure out the error. Please help me!!!

#12 Sent by PkLab 07-02-2017

@Yashvardhan the error message: the configuration is incomplete. Check error messages and the error log file to investigate. btw The article has been updated with right path of opencv source. Try again from cmake

#13 Sent by Nathaniel 08-03-2017

This was the greatest thing anyone has ever done

#14 Sent by PkLab 08-03-2017

I would thank all for kind comments

#15 Sent by Adamco77 22-03-2017

When I try to build the cpp file, opencv is not found in the pkg-config. Maybe someone would help me :)

#16 Sent by adamco77 23-03-2017

Ok, I finally resolve my problem but now when I try to execute the c++ program, the raspberry said the instruction is not allowed. How can I have the right on my raspberry ? thanks ! :D

#17 Sent by Espen Börde 01-04-2017

Hi. Thank you for a very good and clear turtorial. However, I still have some issues and I get the error msg driven by the if statement:
Code:
(!cap.isOpened()) {
cerr << "ERROR: Unable to open the camera" << endl;
I did the following step:
From terminal window on my Mac
1: I followed your instructions and ran $ python3. It was OK
2: I ran: raspistill -o testpic_3. Picture was created
3: I ran raspivid -o testvid.h264 -t 10000. Video was created

What is wrong ?

#18 Sent by PkLab 01-04-2017

@Espen Börde
To use cv::VideoCapture class you need of Video4Linux library
- Did you install the Video4Linux library as suggested in the tutorial
- what with tests as point 5) Test: try to grab a single frame and check for the file

#19 Sent by Espen Börde 01-04-2017

Strange. I compiled everything successfully yesterday. Today, I wanted to re-compile but using a virtual env on the same Pi as I used yesterday. This is what I did. I re-formated my USB and re-mounted it as usbmem_1 and created a viitual environment (cv). By doing the re-formating I had expect that all previous installed OpenCV and Python data on my system should be removed. However after a while compuling OpenCV I got the following error msg: /home/pi/usbmem_1/opencv/opencv 3.2.0/build/modules/calib3d/precomp.hpp:144:70: fatal error: can’t write PCH file: No space left on device. when running df -h I can see that /dev/root is almost used 100%, while my USB mem is almost empty. Any thoughts what can be wrong, and how can I come back to initial installation?

#20 Sent by PkLab 01-04-2017

@Espen Börde
PCH files are generated in the build/modules directory therefore if the build dir is under the USB you shouldn't have the problem.
Is /home/pi/usbmem_1 the right mounting point of your USB ?

BTW reformatting USB will removes files on USB, but if you had make "make install" the compiled library files (20Meg ?) are copied by default in:
Code:
/usr/local/lib/libcv*
/usr/local/include/opencv
/usr/local/bin/opencv
/usr/local/lib/python2.7/dist-packages/cv*
/usr/local/lib/python3.4/dist-packages/cv*

#21 Sent by Espen Börde 02-04-2017

My previous questions are solved, and I have succeeded running through the entire installation process. However, when I type the cmd: python3, it gives me the following output: Python 2.7.9 (default, Sep 17 2016, 20:26:04). What is wrong? Espen

#22 Sent by PkLab 05-04-2017

@Espen Börde Maybe you have some mistake with your Python virtualenv

#23 Sent by Fathur 08-04-2017

Installation Succesfull, with some editing on cmake
but i'm getting error when using opencv
when import cv2 (python)
that was error
illegal instruction

#24 Sent by leonnoel 15-05-2017

I have completed the installation on a Pi3. the code compled in about 45 minutes. When testing with Python 2.7 it would not import cv2 but would import numpy as np. Both would be imported with Python3. What should do? Thank you.

#25 Sent by MatAff 07-06-2017

I agree with Nathaniel...
This tutorial guided me through the installation process very smoothly. The main thing I did differently was use:
Code:
make

instead of
Code:
make -j4

I ran this a couple of times with the -j4 addition (which as far as I understand uses a multicore process) and I kept getting errors. This first time I ran it with just 'make' it ran without errors.

#26 Sent by ElliottJ 08-08-2017

Loved the simplicity of this tutorial! everything worked exactly as instructed. hardware used, raspbery pi 3, with 8gb micro sd card and fish eye camera, raspbian Jessie

#27 Sent by pklab 08-08-2017

@ElliottJ Thank you for your nice comment !

#28 Sent by Nadav B 20-09-2017

Great post. Can you specify in the post what version of g++ and gcc you have used? We are getting segmentation fault when doing the make. (We use g++ version 6.3)

#29 Sent by Ruchir 30-09-2017

It not working on RPi 3 ,at 100% it stop and green and red led on hold.But working fine on Noobs desktop image .

#30 Sent by TOTORO 07-10-2017

Great article!
I had some trouble in make and I found USB format using 'fdisk' do not change my file format from 'vfat' to 'ext4'. This may cause a error in 'make -j4' steps.
The method using "Disks" from launcher worked for me.
Thank you

#31 Sent by Anonymous 11-10-2017

All step successful. There is a problem:\r\nWhy there is \"Illegal Instruction\" appear when i import cv2 in python3? How to fix it?

#32 Sent by daniel 13-10-2017

cv2.error: /home/pi/opencv-3.2.0/modules/highgui/src/window.cpp:577: error: (-2) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function cvDestroyAllWindows

#33 Sent by Dinushan Paranavithana 13-10-2017

According to the steps under 'Video4Linux' subheading, is it possible to code in C++ instead of using python, to access the raspberry pi camera module for live video?
For an Example: using this piece of code -> VideoCapture cap(0);
we can access the webcam using C++. So is it the same code that we should use to access raspberry pi camera module?

#34 Sent by PkLab 14-10-2017

@Paranavithana Yes you can also use VideoCapture cap(0); with C++

#35 Sent by Dinushan Paranavithana 29-10-2017

Thank You! Sorry for the delay......

#36 Sent by karl 25-11-2017

hello I have built for rpi 1B running raspian and it worked well
I am using c++
I have written test app

as soon as I link in any of the libraries I receive illegal instruction error when running compiled executable

#37 Sent by karl 26-11-2017

Its ok I compiled it with options for ARM7 when I am running ARM6. Thanks!

Leave your comment:

Note:
  • Your email email will not be visible or used in any way, and is not required
  • Please keep comments relevant
  • Any content deemed inappropriate or offensive may be edited and/or deleted
  • HTML code is not allowed. Please use BBCode to format your text
    [b]bold[/b], [u]underline[/u], [i]italic[/i], [code]code[/code]
The coding examples presented here are for illustration purposes only. The author takes no responsibility for end-user use
This work is property of Pk Lab. You can use it for free but you must retain author's copyright.