Installare OpenCV 3.2 Python/C++ su Raspberry PI
Raspberry PI è un sistema meraviglioso, OpenCV è una eccezionale libreria per Computer Vision . Questa è la nostra guida su come installare e configurare OpenCV 3.2.0 per Python/C++ sul Raspberry PI 2 con Raspbian Jessie. Sulla rete sono disponibili diverse guide su questo argomento ma molte non sono in Italiano o sono incomplete o fanno riferimento a vecchie versioni.

Per usare l'ultima versione di OpenCV è necessario compilare OpenCV a partire dai sorgenti utilizzando CMake. Questa è una operazione semplice ma sono richiesti numerosi passaggi. Le informazioni che seguono si riferiscono alla versione 3.2.0 di OpenCV ma sono valide anche per la 3.1.0.
Rimuovere la versione predefinita (vecchia) di OpenCV
In Raspbian è preinstallato OpenCV ver. 2.4.9. Anche se questa versione è un po datata gli utenti possono utilizzarla per iniziare a fare pratica. Andando avanti con la Computer Visione arriva presto il momento in cui è necessario installare l'ultima versione di OpenCV.
Arrivati a questo punto è preferibile rimuovere la vecchia versione preinstallata con:
sudo apt-get remove libopencv* sudo apt-get autoremove
Hai spazio sufficiente ?
Ci stiamo preparando a .scaricare e compilare OpenCV 3.2.0 da zero Questa operazione richiede almeno 2GB di spazio temporaneo per la sola distribuzione di Release. E' abbastanza comune non avere spazio sufficiente sul proprio Raspberry PI... prima di continuare controlla lo spazio disponibile con:
df -h
Filesystem Size Used Avail Use% Mounted on
/dev/root 6.1G 5.1G 673M 89% /
devtmpfs 427M 0 427M 0% /dev
...
In questo caso sono disponibili solo 673MB !
La soluzione è utilizzare un disco o una memoria esterna USB in cui scaricare e compilare OpenCV. Al termine delle operazioni la memoria può essere rimossa o cancellata.
CMake Error: cmake_symlink_library: System Error: Operation not permitted
Questo perché la compilazione utilizza link simbolici non disponibili sulle partizioni Windows.
Se è disponibile spazio sufficiente sul proprio Raspberry PI oppure si ha già disponibile una memoria esterna formattata Linux è possibile saltare il paragrafo che segue.
Formattare una memoria USB come partizione Linux
- Inserisci una memoria USB di almeno 2GB nel tuo Raspberry PI e identifica il nome assegnato al device. Un nome tipico è
/dev/sda1
. Utilizza lsblk per la visualizzare lista dei device presenti sul tuo 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 /
- Assicurati che la memoria non sia già montata, in caso smontala con:
sudo umonut /dev/nome-device
- Crea una partizione Linux con la seguente procedura:
sudo fdisk /dev/nome-device
- Mostra la lista delle partizioni disponibili con il comando p
- Elimina le partizioni presenti con il comando d per ogni partizione
- Crea una nuova partizione con il comando c
- Mostra la lista delle partizioni disponibili con il comando p
- Assicurati che la partizione sia del tipo Linux. In caso modifica il tipo con il comando t
- Salva le modifiche ed esci con il comando w
- Formatta la nuova partizione con:
sudo mkfs -t ext2 /dev/nome-device
- Crea una cartella in cui montare la memoria e monta la memoria:
mkdir ~/usbmem sudo mount /dev/nome-device /home/pi/usbmem
A questo punto utilizzeremo la cartella /home/pi/usbmem
come directory di lavoro per i prossimi passaggi.
Installazione dei prerequisiti
Aggiorna il tuo sistema
sudo apt-get update sudo apt-get upgrade sudo rpi-update sudo reboot
Questa operazione può richiedere diverso tempo se il tuo sistema non è aggiornato. Al termine riavvia il sistema.
Installazione degli strumenti di sviluppo
sudo apt-get install build-essential cmake cmake-curses-gui pkg-config
Installazione delle librerie
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 gestisce la camera Raspberry PI attraverso il modulo picamera
. E' possibile utilizzare questo modulo anche con OpenCV ma è necessario acquisire l'immagine in un numpy.array
e poi mappare l'array in una Mat OpenCV .
Per usare l'acquisizione standard cv2.VideoCapture(0)
con la raspicam è necessario il driver Video4Linux.
- Verifica dei prerequisiti (da controllare con sudo raspi-config):
- La camera sia attivata
- Impostare una abbondante memoria per
gpu_mem
(InAdvance Options > Memmory Split
set 128 min)
- Installazione della libreria v4l dal repository:
sudo apt-get -y install libv4l-dev v4l-utils
- Attivazione del modulo del kernel:
sudo modprobe bcm2835-v4l2
- Test del modulo con:
v4l2-ctl --list-devices
Dovrebbe comparire qualcosa simile a:mmal service 16.1 (platform:bcm2835-v4l2): /dev/video0
- Prova: acquisizione di una singola immagine in
~/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
- Informazioni: Verifica tutti i controlli disponibili quali brightness, contrast,.. con
v4l2-ctl --list-ctrls
Se tutto ha funzionato correttamente aggiungi il nome del modulo bcm2835-v4l2
alla lista dei moduli caricati all'avvio in /etc/modules-load.d/modules.conf
Installazione di librerie aggiuntive
Queste librerie non sono obbligatorie ma possono migliorare le prestazioni di OpenCV
sudo apt-get install libatlas-base-dev gfortran
Setup di Python
Con Raspbian Jessie sono disponibili sia Python 2.7 che Python 3. In questa guida verrà installato OpenCV 3.2.0 per entrambe le versioni di Python.
Considerato che il nostro Raspberry PI è dedicato ad OpenCV non utilizzeremo virtualenv in questa guida.
Installazione di python-dev & numpy
sudo apt-get install python2.7-dev python2-numpy sudo apt-get install python3-dev python3-numpy
Si parte con OpenCV
Nei prossimi passi scarichiamo, configuriamo, compiliamo ed installiamo OpenCV.
Download di OpenCV
Ricorda che sono necessari almeno 2GB di spazio di lavoro temporaneo. In questa guida utilizziamo una memoria USB esterna montata 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
Installeremo anche opencv_contrib
benché questo repository contiene moduli che possono avere funzioni non stabili o non ben testate.
Unzip dei file
cd ~/usbmem/opencv unzip opencv_source.zip unzip opencv_contrib.zip
Compila e installa OpenCV
Per compilare OpenCV per C++, Python2 e Python3 è necessario utilizzare CMake. OpenCV ha molte opzioni di configurazione che possono essere scelte al momento della compilazione. E' possibile impostare la configurazione tramite linea di comando e rivedere o modificare la configurazione (prima di compilare) tramite il comando ccmake (che è una interfaccia utente di tipo testo)
Creazione della directory di lavoro:
cd /home/pi/usbmem/opencv/opencv-3.2.0 mkdir build cd build
Avvio della configurazione tramite linea di comando
Di seguito la nostra configurazione predefinita. Non siamo interessati ad una versione di Debug ne ai Test. Suggeriamo di attivare le ottimizzazioni NEON per il processore for ARM Cortex in modo da incrementare (un po) le prestazioni di OpenCV.
cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -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 \ ../
Dovrebbe apparire:
.....
-- Configuring done
-- Generating done
-- Build files have been written to: /home/pi/usbmem/opencv/opencv-3.2.0/build
Se non compare Generating done
allora c'e' stato un problema durante la creazione della configurazione. Leggere i messaggi di errore ed eventualmente il file di log indicato per cercare causa del problema.
Se tutto si conclude regolarmente e accettate la nostra configurazione predefinita potete saltare il paragrafo successivo.
Verifica/modifica la configurazione tramite interfaccia utente
E' possibile modificare la configurazione modificando le opzioni dalla linea di comando come al paragrafo precedente oppure utilizzare l'interfaccia utente ccmakeper configurare tutte le opzioni disponibili:
$ 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)
Scorrere la lista e modificare le opzioni desiderate.
Al termine premere c per configurare. In assenza di errori premere g per generare il makefile
.
Compilazione di OpenCV
Ok si parte con la compilazione (utilizzare l'opzione -jn
per attivare la compilazione su n thread):
make -j4
Questa fase richiede molto tempo... in caso di errori il processo di ferma altrimenti dopo circa 2 ore (con Raspberry PI 2) dovrebbe comparire:
[100%] Built target ...
Installazione di OpenCV
Pochi passaggi veloci con:
sudo make install sudo ldconfig
Congratulazioni, il tuo Raspberry PI è pronto per la Computer Vision ! Per default file vengono installati 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 della installazione
Test con Python 2 o Python 3
Da una finestra terminale eseguire run python, import cv2 e print della versione:
$ 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 della acquisizione live.... dalla interfaccia grafica eseguire idle3
(or idle2), creare un nuovo 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()
Esegui il file con F5 e... la finestra Live dovrebbe apparire sul desktop!
Vedi altri esempi di OpenCV in python in: /usr/local/share/OpenCV/samples/python
Test con C++
Test della acquisizione live.... dalla interfaccia grafica creare un nuovo 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; }
Compila con:
g++ $(pkg-config --libs --cflags opencv) -o SimpleGrab SimpleGrab.cpp
Esegui con ./SimpleGrab e... la finestra Live dovrebbe apparire sul desktop! Vedi altri esempi di OpenCV in python in: /usr/local/share/OpenCV/samples
Riconoscimenti
Qui alcuni link utili sullo stesso argomento:
- How to install OpenCV 3 on Raspbian Jessie by on pyimagesearch
- Installing OpenCV 3.1 on Raspbian Jessie by willprice on GitHub
47 Commenti:
#1 Inviato da 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 Inviato da 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 Inviato da 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 Inviato da 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 Inviato da 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 Inviato da Mert Kahyaoğlu 19-12-2016
Thank you for step by step explantion.
All process was working well.
#7 Inviato da 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 Inviato da 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 Inviato da 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 Inviato da PkLab 31-01-2017
@K13 Solution is in the article:
Code: sudo apt-get install python3-dev python3-numpy
#11 Inviato da 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 Inviato da 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 Inviato da Nathaniel 08-03-2017
This was the greatest thing anyone has ever done
#14 Inviato da PkLab 08-03-2017
I would thank all for kind comments
#15 Inviato da 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 Inviato da 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 Inviato da 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:
I did the following step:
Code: (!cap.isOpened()) {
cerr << "ERROR: Unable to open the camera" << endl;
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 Inviato da 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 Inviato da 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 Inviato da 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 Inviato da 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 Inviato da PkLab 05-04-2017
@Espen Börde Maybe you have some mistake with your Python virtualenv
#23 Inviato da 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 Inviato da 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 Inviato da 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 Inviato da 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 Inviato da pklab 08-08-2017
@ElliottJ Thank you for your nice comment !
#28 Inviato da 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 Inviato da 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 Inviato da 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 Inviato da 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 Inviato da 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 Inviato da 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 Inviato da PkLab 14-10-2017
@Paranavithana Yes you can also use VideoCapture cap(0); with C++
#35 Inviato da Dinushan Paranavithana 29-10-2017
Thank You! Sorry for the delay......
#36 Inviato da 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 Inviato da karl 26-11-2017
Its ok I compiled it with options for ARM7 when I am running ARM6. Thanks!
#38 Inviato da Bart 13-01-2018
Ty so much!Spent days to solve the lack of diskspace problem, but u saved my day! Tyvm
#39 Inviato da Jorge Imperial 19-01-2018
Works like a charm on RPI3. Thanks for your post!
#40 Inviato da 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 Inviato da 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 Inviato da Walter 19-02-2018
Good
#43 Inviato da 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 Inviato da 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 Inviato da 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: www.bitpi.co/2015/02/11/how-to-change-raspberry-pis-swapfile-size-on-rasbian/ this avoids the system to freeze at 100% and you can use make -j4\r\n- Install numpy for python2 see: askubuntu.com/questions/868599/how-to-install-scipy-and-numpy-on-ubuntu-16-04 (numpy is not supported for python2)\r\nHope it helps\r\n\r\n
#46 Inviato da 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 Inviato da 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..
Questo materiale è di proprietà di Pk Lab ed è utilizzabile liberamente a condizione di citarne la fonte.