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:
    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 \


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):
  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 -O
wget -O

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

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.

	-D BUILD_opencv_ts=OFF \
	-D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-3.2.0/modules \

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 ..
 BUILD_CUDA_STUBS                 OFF
 BUILD_DOCS                       OFF
 BUILD_EXAMPLES                   OFF
 BUILD_JASPER                     ON
 BUILD_JPEG                       ON
 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:


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__)

Test live grabbing... from your graphic interface run idle3 (or idle2), create a new file ~/ocv-tests/

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
if cap.isOpened() == False:
    print('Unable to open the camera')
    print('Start grabbing, press a key on Live window to terminate')
    while( cap.isOpened() ):
        ret,frame =
        if ret==False:
            print('Unable to grab from the camera')
        key = cv2.waitKey(5)
        if key==255: key=-1 #Solve bug in 3.2.0
        if key >= 0:
    print('Closing the camera')
print('bye bye!')

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;
    int key = cv::waitKey(5);
    key = (key==255) ? -1 : key; //#Solve bug in 3.2.0
    if (key>=0)
  cout << "Closing the camera" << endl;
  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/


Here some useful link on same subject

Vote this page:


#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.

#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

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:
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:
(!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:

#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:

instead of
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!

#38 Sent by Bart 13-01-2018

Ty so much!Spent days to solve the lack of diskspace problem, but u saved my day! Tyvm

#39 Sent by Jorge Imperial 19-01-2018

Works like a charm on RPI3. Thanks for your post!

#40 Sent by Aditya Rawas 20-01-2018

make: *** No targets specified and no makefile found. Stop.\r\n\r\nWhat is this error I am not able to figure out please replay me I need this to me fixed

#41 Sent by david 07-02-2018

Working perfectly on rpi 3. I needed to change make -j4 to make -j1, otherwise it got frozen just at the end of the process.

Thank you very much.

#42 Sent by Walter 19-02-2018


#43 Sent by Walter 19-02-2018

The procedure is prefect for my Raspberry Pi 3 Model B. I used a 16GB SD card instead of USB memory device. However, I also needed to change the instruction of "3 -j4" to "make -j1", otherwise, the system would be frozen at the end of the process.

#44 Sent by Walter 19-02-2018

(I tried twice times with the instruction of "make -j4", it always stopped at 99%). I also followed the procedures discussed in other websites before, however, they were not successful.

Thank you!

#45 Sent by Jean-Pierre 25-03-2018

Build it with 3.4.0 on a 32GB SD to be successful I had to change:\r\n- The swap file size see: this avoids the system to freeze at 100% and you can use make -j4\r\n- Install numpy for python2 see: (numpy is not supported for python2)\r\nHope it helps\r\n\r\n

#46 Sent by Anton 07-04-2018

I had the same problem with the "make -j4" instruction, i changed it to "make -j1" to make it work. That way your cpu will only be at 25% .
However, when the build is at 60% i get the following messages:
[ 60%] Linking CXX executable ../../../../bin/opencv_waldboost_detector
followed by a bunch of undefined references.
Any solutions?

#47 Sent by Kamal Chandra Upreti 14-04-2018

Dear Sir. I am building on Ubuntu running on Raspberry pi 3.. The system freezes when it reaches 100 % and both LEDs lights up solid.. Please reply the solution..

#48 Sent by seop 30-05-2018

I solved the problem that mr. Kamal Chandra Upreti had
I tried many times with 4 pieces of raspberry pi 3.
and I was shown with this error message


Scanning dependencies of target opencv_python3
Scanning dependencies of target opencv_python2
[100%] Building CXX object modules/python2/CMakeFiles/opencv_python2.dir/__/src2/cv2.cpp.o
[100%] Building CXX object modules/python3/CMakeFiles/opencv_python3.dir/__/src2/cv2.cpp.o
virtual memory exhausted: Cannot allocate memory
modules/python2/CMakeFiles/opencv_python2.dir/build.make:320: recipe for target \'modules/python2/CMakeFiles/opencv_python2.dir/__/src2/cv2.cpp.o\' failed
make[2]: *** [modules/python2/CMakeFiles/opencv_python2.dir/__/src2/cv2.cpp.o] Error 1
CMakeFiles/Makefile2:7686: recipe for target \'modules/python2/CMakeFiles/opencv_python2.dir/all\' failed
make[1]: *** [modules/python2/CMakeFiles/opencv_python2.dir/all] Error 2
make[1]: *** Waiting for unfinished jobs....
[100%] Linking CXX shared module ../../lib/python3/
[100%] Built target opencv_python3
Makefile:160: recipe for target \'all\' failed
make: *** [all] Error 2

so I followed up the guide on this link

it's solved!
good luck every developer!

#49 Sent by pooneh 03-07-2018

hi i followed this guide and installed opencv but when I use this command:
it gives me this error: module "cv2.face" has no attribute "fisherfacerecognizer_create()"
where is the problem in your opinion?

#50 Sent by david 13-07-2018

Just made it on opencv 3.4.1 on rpi 3. perfectly fine! thank you very much!

#51 Sent by Henrik 07-09-2018

Hi, Thank you for a very good tutorial.

#52 Sent by Henrik Lauridsen 07-09-2018

I am getting an error in Python 3 IDLE when running your\\r\\nUnable to open the camera The command raspistill -o cam.jpg grabs a picture What can I do to fix this issue Tia, Henrik

#53 Sent by f41thr 15-09-2018

It is worth to mention that the last compilation step python2 and python3 \r\n(./modules/python/src2/cv2.cpp) takes ages on my Raspberry 3+ (using 1024 kb swap and make -j3). So be patient while building your own installation. \r\nMy opencv version ->\r\n\r\n>>> import cv2\r\n>>> print (cv2.__version__)\r\n3.4.1\r\n\r\nAnd this is an excellent installation guide to opencv on Raspberry X. \r\n\r\n \r\n

#54 Sent by ZloyVolk 24-09-2018

How sweet! Thanks a lot!
I plan to only use C++ API, so I omitted everything pertaining to Perl. The build took about 45 minutes. The .cpp example works well. In case anyone cares, here's my configuration:
-DBUILD_opencv_python2=OFF -DBUILD_opencv_python3=OFF \
-DOPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.4.3/modules \
Perhaps, it can be trimmed down further.
Oh, and I forgot to bump up the swap, but it has built (with -j4) smoothly.
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.