- omar
hello, having a problem about Step 7: Finally Ready to be Compile just output
“make: *** No target specified and no makefile found. stop”How can i solve this problem
- Rodo
Thank you very much, bro! Your post is informative and clear for newbie like me ^^.
- jim
This is failing when installing on a fresh install of stretch-lite:sudo pip3 install numpy The message is “sudo: pip3: command not found” I’m not sure what the work around is.
- Rafael
Hello Excellent work. I have a question, it is possible to have OpenCV installed simultaneously for the two Python 2.7 & 3.5, greetings.
- Kazim
Great Tutorial!! Thanks a bunch, looking forward to more in the future!
- Alexander
Is there a way to copy the compiled files onto an other Raspberry(same model)? I want to avoid recompilation on a different pi
- Josué Juárez
Gracias sigue haciendo tu trabajo
Thank you, keep doing your job - rubentxo
I want to thank for your step by step tutorial! It’s the best one!
Great work!!! I’ll follow your blog! - dongo
hello, i have a problem step 5
github not found - Francesco Garavaglia
Hi!
I’m having problems with Step 10: Testing OpenCV 3.4.0 install
This is what I get:pi@raspberrypi:~ $ python3
Python 3.5.3 (default, Jan 19 2017, 14:11:04)
on linux
Type “help”, “copyright”, “credits” or “license” for more information.
>>> import cv2
Traceback (most recent call last):
File “”, line 1, in
File “/home/pi/.local/lib/python3.5/site-packages/cv2/__init__.py”, line 4, in
from .cv2 import *
ImportError: libQtGui.so.4: cannot open shared object file: No such file or directory- Life2Coding Post author
Watch the youtube video tutorial properly. I think you missed any of the steps that why it is not getting the OpenCV Library
- Francesco Garavaglia
I retried, but nothing changes. I saw that the unique difference occurs during “Step 6: Compile and Install OpenCV 3.4.0 for Python 3” when I got this:
— Python 3:
— Interpreter: /usr/bin/python3 (ver 3.5.3)
— Libraries: /usr/lib/arm-linux-gnueabihf/libpython3.5m.so (ver 3.5.3)
— numpy: /home/pi/.local/lib/python3.5/site-packages/numpy/core/include (ver 1.14.2)
— packages path: lib/python3.5/dist-packagesLooking at numpy I got site-packages instead of dist-packages. I think that’s the problem!
What do you think? Sorry, but I’m a newbie 🙂- Francesco Garavaglia
- Nithin Bharadwaj
Could you please elaborate on how you solved the above issue? I am getting the same error, and am not able to resolve it. Please help!
- Elliot Harris
Hi Francesco how did you resolve this issue
- Aethan
Same as Nithin. We have the same issue and wonder what you did to fix it. Can you or Life2Coding explain us what to do ?
- Life2Coding Post author
What is yours’ exact problem? Can you elaborate a little bit?
- Nitin Shrivastava
- Nithin Bharadwaj
- D@R:-)
sudo apt install libqt4-test
- Francesco Garavaglia
- Francesco Garavaglia
- Life2Coding Post author
- Matt Miller
Thanks for making a Python3 set of instructions
I used make instead of make -j4 as I’ve had problems in the past compiling previous versions of openCV and it worked 1st time. - Steven Blue
at the end of step 6 i get (configuring incomplete, errors occured!)
what can i do about that??? - hung
Hi I Install Image I/O packages
sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev -y
An error occurred…….
Reading package lists… Done
Building dependency tree
Reading state information… Done
Package libpng12-dev is not available, but is referred to by another package.E: Unable to locate package libjasper-dev
E: Package ‘libpng12-dev’ has no installation candidate - hilda
at step 1 i got (Your partition layout is not currently supported by this tool. You are probably using NOOBS, in which case your root filesystem is already expanded anyway)
because i installed using NOOBS , should i install raspbian stretch ? please help me, thankyou - Nithin Bharadwaj
Hi,
I am receiving the same error. I did a clean installation of OpenCV 3.4 on Raspberry Pi 3. After the installation, I went into the Python3 virtualenv and checked for OpenCV installation by doing, “import CV2” and then a “cv2.__version__”. It worked when I was inside the OpenCV build folder. Now, I came out of it and am in the home directory, and I get a syntax error for “Import cv2”. Please help. - Vishal Kaul
Thanks for the post, it’s helpful!
- Trong Hai
Thanks. Your post helps me so much.
- sleman
i followed your steps in this tutorial to use opencv in face recognition but when i use the command
recognizer = cv2.createLBPHFaceRecognizer()
or
recognizer = cv2.face.LBPHFaceRecognizer_create()
it gives me errors - Vaisakh
[ 65%] Linking CXX executable ../../bin/opencv_traincascade
../../lib/libopencv_imgcodecs.so.3.4.0: undefined reference to WebPFlipBuffer"
../../lib/libopencv_core.so.3.4.0: undefined reference to carotene_o4t::absDiff(carotene_o4t::Size2D const&, unsigned char const*, int, unsigned char const*, int, unsigned char*, int)’
../../lib/libopencv_imgcodecs.so.3.4.0: undefined reference to WebPDeallocateAlphaMemory"
../../lib/libopencv_core.so.3.4.0: undefined reference to carotene_o4t::absDiff(carotene_o4t::Size2D const&, unsigned short const*, int, unsigned short const*, int, unsigned short*, int)’
../../lib/libopencv_core.so.3.4.0: undefined reference to carotene_o4t::absDiff(carotene_o4t::Size2D const&, signed char const*, int, signed char const*, int, signed char*, int)"
../../lib/libopencv_imgcodecs.so.3.4.0: undefined reference to WebPAvoidSlowMemory’
../../lib/libopencv_core.so.3.4.0: undefined reference to carotene_o4t::absDiff(carotene_o4t::Size2D const&, float const*, int, float const*, int, float*, int)"
../../lib/libopencv_imgcodecs.so.3.4.0: undefined reference to WebPCopyDecBuffer’
../../lib/libopencv_imgcodecs.so.3.4.0: undefined reference to WebPAllocateDecBuffer"
../../lib/libopencv_imgcodecs.so.3.4.0: undefined reference to WebPCopyDecBufferPixels’
../../lib/libopencv_core.so.3.4.0: undefined reference to carotene_o4t::absDiff(carotene_o4t::Size2D const&, short const*, int, short const*, int, short*, int)"
../../lib/libopencv_core.so.3.4.0: undefined reference to carotene_o4t::absDiff(carotene_o4t::Size2D const&, int const*, int, int const*, int, int*, int)’
../../lib/libopencv_imgcodecs.so.3.4.0: undefined reference to `VP8DecompressAlphaRows’
apps/traincascade/CMakeFiles/opencv_traincascade.dir/build.make:389: recipe for target ‘bin/opencv_traincascade’ failedi got this error when i was installing opencv on my rpi b+ model running with rasbian stretch. please help me
- Iker
I have a problem in the step 9.
pip pip-10.0.1.dist-info
- Nathaniel
Just make sure you have some way of cooling your pi down because it will get really hot!
- Nitin Shrivastava
CMake Error: The source directory “/home/pi” does not appear to contain CMakeLists.txt.
it shows this error….please help
- wannaBrobot
Great tutorial, best I’ve seen! Here is a tip for anyone getting the
E: Unable to locate package ______
E: Package ‘_______’ has no installation candidateerror and how I fixed it.
SPECS:
Raspberry Pi 3B, OS: Raspbian, Version: 9 (Stretch)1) sudo nano /etc/apt/sources.list
a) Uncomment “deb-src http://raspbian.raspberrypi.org/raspbian/ stretch main contrib non-free rpi”2) sudo nano /etc/apt/sources.list.d/raspi.list
a) Uncomment “deb-src http://archive.raspberrypi.org/debian/ stretch main ui”
b) Press ctrl-o, then enter, then ctrl-x3) sudo apt-get update
4) sudo apt-get upgrade
5) sudo apt-get upgrade –fix-missing6) Do steps 3-5 two to three times.
a) The problem is that with the above two lines commented out apt-get was not caching the proper packages. By updating and upgrading apt-get you are allowing it to refresh and store the poroper packages. - Abdulbasit
If you just uploded the SD card image for us it would be the greatest work done for OpenCV&RPi users
- Mang
problem in the step 9.
The compilation of OpenCV was well done, but in the verification step, over the directoy “/usr/local/lib/python3./usr/local/lib/python3.5/dist-packages” if i execute the “ls” command, the next appears:
pip pip-10.0.1.dist-info
So, when i trying to change the name of cv2.cpython-35m-arm-linux-gnueabihf.so by cv2.so, it says “mv: cannot stat ‘/usr/local/lib/python3.5/dist-packages/cv2.cpython-35m-arm-linux-gnueabihf.so’: No such file or directory”
Got the same, once it was a compilation error so no cv2…so file was created. Next time it was placed in /site-packages/
Next I forgot which environment I was in, was in the hidden /cv catalog. - Jose Esquivel
I am having an issure with step 9. I keep getting the ” no such file or directory ”. Can you help me figure our what is wrong. Thank you.
pi@raspberrypi:~/opencv-3.4.0/build $ ls -l /usr/local/lib/python3.5/dist-packages/
ls: cannot access /usr/local/lib/python3.5/dist-packages/: No such file or directory
pi@raspberrypi:~/opencv-3.4.0/build $ ls -l /usr/local/lib/python3.5/site-packages/
ls: cannot access /usr/local/lib/python3.5/site-packages/: No such file or directory - Kay Zazz
error: (-215) scn == 3 || scn == 4 in function cvtColor
This error occurs when I use opencv on raspberry pi.
How can I fix this nontype error?
Reply me - putri
i got a problem, i follow the step i stuck on compiling with the command make -j4 , and i got this. can you help me???
[ 38%] Linking CXX shared library ../../lib/libopencv_ml.so
CMakeFiles/opencv_ml.dir/src/lr.cpp.o: file not recognized: File truncated
collect2: error: ld returned 1 exit status
modules/ml/CMakeFiles/opencv_ml.dir/build.make:460: recipe for target ‘lib/libopencv_ml.so.3.4.0’ failed
make: *** Error 1
CMakeFiles/Makefile2:1889: recipe for target ‘modules/ml/CMakeFiles/opencv_ml.dir/all’ failed
make: *** Error 2
[ 43%] Built target opencv_imgproc
make: *** Error 2 - ambhub
hi.. pls i am having raspbian stretch installed… i followed through all the tutorial but i got stucked at the building of opencv….
fatal error: can’t write PCH file: No space left on device
}
^
compilation terminated.
modules/bgsegm/CMakeFiles/pch_Generate_opencv_test_bgsegm.dir/build.make:62: recipe for target ‘modules/bgsegm/test_precomp.hpp.gch/opencv_test_bgsegm_RELEASE.gch’ failed
make: *** Error 1
CMakeFiles/Makefile2:6336: recipe for target ‘modules/bgsegm/CMakeFiles/pch_Generate_opencv_test_bgsegm.dir/all’ failed
make: *** Error 2
Makefile:160: recipe for target ‘all’ failed
make: *** Error 2 space error even though i used both make -j4 and make. i have an 8gig memory card. thanks - Jeon Nora
Hello, I am just a beginner to Raspberry Pi and I wanted to install opencv to my raspberry pi 3 and I have got the error on Step 3:Install Dependencies!
At that step, Install CMAKE developer packages, when I write this command,
sudo apt-get install build-essential cmake pkg-config -y
I got this error!
Package cmake is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another sourceE: Package ‘cmake’ has no installation candidate
I am currently using “Raspbian GNU/Linux 9 (stretch)”.
- Lafleur
Hello 🙂
Just to precise I’m working on a orange pi on Rasbian.
I have a probleme at step 6.
Here is the error message:
CMake Error at CMakeLists.txt:29 (cmake_minimum_required):
CMake 2.8.12.2 or higher is required. You are running version 2.8.9I’ve tried several times to update and upgrade. I didn’t forget the sudo apt-get upgrade –fixe-missing.
I’ve tried also apt-get install cmake and it’s return:
” Building dependency tree
Reading state information… Done Helawe B. Javier GaitánHi ¡ i just want to thank you for the tutorial it was very useful. Keep going with that kind attitude to help others who like this stuff
- Azad
I have problem in Step: 7
Show below message:
CMakeFiles/opencv_imgcodecs.dir/src/grfmt_exr.cpp.o: file not recognized: File truncated
collect2: error: ld returned 1 exit status
modules/imgcodecs/CMakeFiles/opencv_imgcodecs.dir/build.make:578: recipe for target ‘lib/libopencv_imgcodecs.so.3.4.0’ failed
make: *** Error 1
CMakeFiles/Makefile2:2505: recipe for target ‘modules/imgcodecs/CMakeFiles/opencv_imgcodecs.dir/all’ failed
make: *** Error 2
make: *** Waiting for unfinished jobs….
[ 56%] Built target opencv_dnn
Makefile:160: recipe for target ‘all’ failed
make: *** Error 2Please give me a solution. I try make -j4 and only make also but show same message when come in this state(56%).
- Suchitra
Hi, I got these error. Could you please help?
[ 67%] Building CXX object modules/xfeatures2d/CMakeFiles/opencv_xfeatures2d.dir/src/vgg.cpp.o
/tmp/ccXSlohP.s: Assembler messages:
/tmp/ccXSlohP.s: Fatal error: can’t write 3996 bytes to section .rodata._ZZN2cv11xfeatures2d8VGG_ImplC4EifbbfbE2PJ_2 of CMakeFiles/opencv_xfeatures2d.dir/src/vgg.cpp.o because: ‘No space left on device’
/tmp/ccXSlohP.s: Fatal error: can’t close CMakeFiles/opencv_xfeatures2d.dir/src/vgg.cpp.o: No space left on device
modules/xfeatures2d/CMakeFiles/opencv_xfeatures2d.dir/build.make:595: recipe for target ‘modules/xfeatures2d/CMakeFiles/opencv_xfeatures2d.dir/src/vgg.cpp.o’ failed
make: *** Error 1
CMakeFiles/Makefile2:13645: recipe for target ‘modules/xfeatures2d/CMakeFiles/opencv_xfeatures2d.dir/all’ failed
make: *** Error 2
Makefile:160: recipe for target ‘all’ failed
make: *** Error 2
pi@raspberrypi:~/opencv-3.
Anyone who has dealt with image processing in relation to the Raspberry Pi will sooner or later come across the OpenCV library. It provides many very useful features such as face recognition, the creation of depth maps (stereo vision, optical flow), text recognition or even for machine learning. In addition, OpenCV (Open Source Computer Vision) can be integrated into both its C ++ files and its Python scripts.
Especially in terms of feature recognition in images taken by the Raspberry Pi, OpenCV is very helpful.
This advanced tutorial shows how to install OpenCV on the Raspberry Pi and how to integrate it into Python.
For the time being, I would like to recommend everyone a Raspberry Pi Model B to use, because this is a lot more powerful than its predecessor. Even on a Raspberry Pi B + compiling takes about 6 times as long, with a Pi 2 in total “only” takes about an hour.
First of all, we update the package lists:
sudo apt - get update && sudo apt - get upgrade && sudo rpi - updateA reboot is necessary if it has been updated.
Sudo reboot
Then you can install all the important tools and libraries needed for OpenCV (installation takes a few minutes).
sudo apt - get install build - essential git cmake pkg - config libjpeg8- dev libtiff4 - dev libjasper - dev libpng12 - dev libavcodec- dev libavformat - dev libswscale - dev libv4l - dev libgtk2. 0 - dev libatlas- base - dev gfortranIf everything worked, we could clone OpenCV from git . This step also takes a few minutes.
git clone https : / / github .com / Itseez / opencv .git && cd opencv &&git checkout 3.0.0Whether version 3.0 or 2.4 of OpenCV is taken is up to you. Depending on the application, one of the versions may be better suited.
Afterwards, OpenCV can be compiled. You can either use Python 2.7 or Python 3+. There are some differences between the versions, especially as some libraries are not (yet) executable with Python 3+. However, this mainly affects smaller libraries, as common libraries (NumPy, SciPy, etc.) usually provide the respective files for both versions.
In this tutorial, I use Python 2.7. If you already have Python installed and want to know which version is installed, you can simply enter python into the console and get the exact version at the beginning (the command for Python 3+ is python3). If you do not have a Python installed, you can install it by following the steps below:
sudo apt - get install python2 . 7 - devWe also need the package management tool pip , which installs NumPy right away:
Cd ~ && wget https : / / bootstrap .pypa .io / get - pip .py && sudo python get - pip .py
Now we can simply install via pip NumPy. NumPy is a library that makes it very easy to perform array operations in Python.
pip install numpyBut now to compile OpenCV. For this purpose, a build folder must be created in which the compiled files land:
Cd ~ / opencv && mkdir build && cd build cmake - D CMAKE_BUILD_TYPE = RELEASE - D CMAKE_INSTALL_PREFIX = / usr / local - D INSTALL_PYTHON_EXAMPLES = ON - D INSTALL_C_EXAMPLES = ON - D OPENCV_EXTRA_MODULES_PATH = ~ / opencv_contrib / modules - D BUILD_EXAMPLES = ON . .
Now you can finally compile. This step takes (depending on Raspberry Pi model) quite a long time (on my Pi 2 about an hour). To use all four cores to compile on the Raspberry Pi 2, type in the following:
make - j4If the compilation has worked without problems, we can install OpenCV:
Sudo make install && sudo ldconfig
OpenCV — это популярная библиотека функций машинного зрения, которые позволяют роботам распознавать объекты окружающего мира. OpenCV применяют для навигации, обнаружения препятствий, распознавания лиц и жестов. В этой статье будет предложена пошаговая инструкция по установке OpenCV на одноплатный компьютер Raspberry Pi 3. Также эта статья предваряет серию уроков, направленных на освоение базовых функций OpenCV.
Шаг 1. Свободное место
OpenCV и различные вспомогательные пакеты в сумме занимают достаточно много места. Настоятельно рекомендуется использовать SD-карту размером не менее 16 Гб. Первое, что необходимо сделать перед установкой OpenCV — расширить файловую систему на весь объём SD-карты. Делается это с помощью меню настройки Raspbian. Заходим в терминал и вводим команду: $ sudo raspi-config Откроется меню, в котором нужно выбрать самый верхний пункт: Жмем Enter, а затем кнопкуШаг 2. Установка зависимостей
Для полноценной работы с OpenCV нам потребуется обновить существующие пакеты и установить ряд новых. Начнем с обновления. $ sudo apt-get update $ sudo apt-get upgrade В зависимости от скорости интернета, данные операции займут около 5-10 минут. Далее устанавливаем в систему cmake и еще несколько полезных штук: $ sudo apt-get install build-essential cmake pkg-config Следом пакеты для работы с известными форматами изображений: $ sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev Пакеты для работы с видео: $ sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev $ sudo apt-get install libxvidcore-dev libx264-dev Пакеты для создания простых экранных форм. Это все тоже потом понадобится. $ sudo apt-get install libgtk2.0-dev Специальные ускоренные операции над матрицами. $ sudo apt-get install libatlas-base-dev gfortran Заголовочные файлы языка python версий 2.7 и 3 $ sudo apt-get install python2.7-dev python3-devШаг 3. Загрузка OpenCV из репозитория
Сначала скачаем архив с самим OpenCV. Для этого перейдем в папку /home/pi/Downloads: $ cd ~/Downloads Загрузим архив с помощью wget и распакуем unzip-ом: $ wget -O opencv.zip https://github.com/opencv/opencv/archive/master.zip $ unzip opencv.zip Следом скачаем пакет с дополнительной всячиной — opencv_contrib. $ wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/master.zip $ unzip opencv_contrib.zipШаг 4. Виртуальное окружение
Перед дальнейшей установкой OpenCV, мы немного наведем порядок. Создадим виртуальное окружение, которое оградит наши дальнейшие эксперименты от основной части операционной системы. Это полезно, на случай если потребуется удалить текущую версию opencv и установить новую. Начнем с установки менеджера пакетов pip: $ wget https://bootstrap.pypa.io/get-pip.py $ sudo python get-pip.py Затем установим менеджер виртуального окружения: $ sudo pip install virtualenv virtualenvwrapper $ sudo rm -rf ~/.cache/pip Добавим пару строчек в профиль пользователя, который хранится в файле ~/.profile: $ echo -e "\n# virtualenv and virtualenvwrapper" >> ~/.profile $ echo "export WORKON_HOME=$HOME/.virtualenvs" >> ~/.profile $ echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.profile Теперь нужно сделать следующие три шага:- закрыть все окна терминалов
- разлогиниться
- снова залогиниться
- открыть терминал и ввести команду: $ source ~/.profile
Последнее, что осталось сделать перед сборкой OpenCV — установка математического пакета NumPy: $ pip install numpy
Шаг 5. Компиляция и установка OpenCV
Находясь в ранее созданном виртуальном окружении, зайдем в папку с исходными кодами OpenCV и выполним команды: $ cd ~/Downloads/opencv-master $ mkdir build $ cd build $ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/Downloads/opencv_contrib-master/modules -D BUILD_EXAMPLES=ON .. В конце процедуры появится список компонентов OpenCV, готовых к установке.Красным выделена секция, посвященная python. Ну а теперь само интересное — сборка бинарников. Не выходя из текущей папки, запускаем команду make: $ make -j4 j4 означает, что мы будем собирать пакет используя все 4 ядра Raspberry Pi. Это сильно ускорит процедуру, но даже при таких условиях сборка займет около полутора часов. Сборка должна завершиться примерно таким вот отчетом:
Примечание. Лично у меня, во время сборки система пару раз зависала наглухо. То есть даже мышь не шевелилась. Помогло выключение/включение питания и повторный запуск сборки с ключом -j2. Последнее, что нужно сделать — установить собранный бинарник в папку с python: $ sudo make install $ sudo ldconfig
Шаг 6. Завершение установки
После установки, в рабочей папке python появится файл cv2.cpython-34m.so, который нужно переименовать во что-то более благозвучное: $ cd /usr/local/lib/python3.4/site-packages/ $ sudo mv cv2.cpython-34m.so cv2.so Чтобы мы могли пользоваться OpenCV, находясь в виртуальном окружении, сделаем там ссылку на получившийся cv2.so: $ cd ~/.virtualenvs/cv/lib/python3.4/site-packages/ $ ln -s /usr/local/lib/python3.4/site-packages/cv2.so cv2.soШаг 7. Проверка
Чтобы проверить правильность установки, зайдем в виртуальное окружение, запустим интерпретатор языка python и попробуем импортировать модуль cv2: $ source ~/.profile $ workon cv $ python >>> import cv2 >>> cv2.__version__ "3.1.0" >>> Вот и всё — OpenCV установлен успешно! В следующих уроках мы будем разбираться с обработкой изображения с видеокамеры, применительно к робототехнике.Недавно при реализации одного из проектов, связанных с распознаванием образов, у нас возникла необходимость установить библиотеку компьютарного зрения OpenCV на одноплатный микрокомпьютер Raspberry PB2.
Порывшись в Сети и потратив некоторое время на эксперименты мы успешно решили эту задачу. В результате получилась небольшая инструкция, которой мы с удовольствием делимся со всеми, кто решит использовать OpenCV на Raspberry.
Итак: установка OpenCV:
В примере мы используем версию opencv 2.4.9.
Для начала нам нужно обновить нашу систему:
sudo apt-get update sudo apt-get upgradeТеперь нам необходимо установить дополнительные библиотеки:
sudo apt-get -y install build-essential cmake cmake-curses-gui pkg-config libpng12-0 libpng12-dev libpng++-dev libpng3 libpnglite-dev zlib1g-dbg zlib1g zlib1g-dev pngtools libtiff4-dev libtiff4 libtiffxx0c2 libtiff-tools libeigen3-dev sudo apt-get -y install libjpeg8 libjpeg8-dev libjpeg8-dbg libjpeg-progs ffmpeg libavcodec-dev libavcodec53 libavformat53 libavformat-dev libgstreamer0.10-0-dbg libgstreamer0.10-0 libgstreamer0.10-dev libxine1-ffmpeg libxine-dev libxine1-bin libunicap2 libunicap2-dev swig libv4l-0 libv4l-dev python-numpy libpython2.6 python-dev python2.6-dev libgtk2.0-dev swig libv4l-0 libv4l-dev libswscale-dev v4l-conf v4l-utils libgtk2.0-0 libgtk2.0-dev pkg-config libxvidcore-dev libx264-dev libavcodec-dev libavformat-dev libqt4-dev libqt4-opengl-dev libjasper-devПосле того как мы закончили устанавливать библиотеки переходим к установке OpenCV. В ходе установки может возникнуть ситуация при которой может не быть какой то библиотеки для Вашей системы и нужно будет смотреть чего не хватает и доставлять дополнительно.
Создаем папку в которую будем скачивать наш архив:
mkdir ~/opt/opencv/ cd ~/opt/opencv wget -O openCV-2.4.9.zip http://sourceforge.net/projects/opencvlibrary/files/opencv-unix/2.4.9/opencv-2.4.9.zip/downloadТеперь нам нужно распаковать наш архив. Для этого используем команду:
unzip openCV-2.4.9.zipВ результате у нас создастся папка openCV-2.4.9. Переходим в нее и создаем папку release
cd openCV-2.4.9 mkdir release cd releaseПришло время провести конфигурацию OpenCV. Если Вам не нужно сторонних настроек то можно воспользоваться конфигурацией по умолчанию (для этого просто жмем клавишу «с»). При запуске ccmake появится список настроек которые можно указать (как показано на картинке ниже)
И так приступим:
ccmake ../(Press "c" if empty cache configuration)
Нажимаем клавишу «с»
Когда прошли установки нажимаем снова клавишу «с» для продолжения и клавишу «g» для генерации makefile.
Теперь все сконфигурировано и осталось нажать make. Этот процесс займет в среднем порядка 10 чесов.
make sudo make installНа этом установка завершена. Осталось проверить работоспособность.
Создаем файл main.cpp
#include
Теперь необходимо создать файл CMakeLists.txt и вписать в него следущее:
Cmake_minimum_required(VERSION 2.8) project(DisplayImage) find_package(OpenCV REQUIRED) add_executable(DisplayImage main.cpp) target_link_libraries(DisplayImage ${OpenCV_LIBS})
Нам осталось только скомпилировать и запустить
cmake . makeЗапускаем
./DisplayImage path_to_photo.jpg
Если все прошло успешно то в результате увидим картинку, которую Вы указали в параметре пути к файлу.
Леонид, прогаммист компании Sidstudio
To install OpenCV on Raspberry Pi, you need Raspberry Pi (Pi2 preferably) , Pi camera, and internet connection to Raspberry Pi.
Copy this image to correct size SD Card. To do this correctly please refers the detailed instructions at https://www.raspberrypi.org/documentation/installation/installing-images/
Now since your SD card is ready, Boot your Pi. First thing you want to do is Enable Camera.
To do this run
Sudo raspi-config
and chose Enable Camera (menu 6) also chose the correct speed for your Raspberry Pi from Overclock option (menu 8).
Reboot your Raspberry Pi. Now its is time to Install python wrapper for OpenCV, to do this run
Sudo apt-get install python-opencv
sudo pip install imutils
Now we are almost done. Let"s test the Pi camera connected to Raspberry Pi for proper operation. For this on command prompt run,
Raspistill -o cam.jpg
The red light on the Pi camera will come on and a picture will be stored in cam.jpg file. Now we are all set to do some serious face tracking using Raspberry Pi. You can download the face tracking sample code using haar cascade from .
You can run this code from Raspberry Pi command line.
Python face_detect.py haarcascade_frontalface_default.xml
If the face is found in an image captured by camera, python program will print "Found 1 faces!. " Below is brief description of how the code work.
From picamera.array import PiRGBArray from picamera import PiCamera import time import cv2 import sys import imutils # Get user supplied values cascPath = sys.argv # Create the haar cascade faceCascade = cv2.CascadeClassifier(cascPath) # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = (160, 120) camera.framerate = 32 rawCapture = PiRGBArray(camera, size=(160, 120))
This imports the required libraries and open the haar cascade file
Raspberry pi camera is intialized and the streme of images is collectd from camera one by one. Resolution is selected to be 162X120 for fast detection of faces.
Image = frame.array gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
each image is picked from the camera and is loaded in nmupy array. Image is then converted to a grayscale image. This gray scale image is fed to facedetection alogorithm, with some minimum size setting
Faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags = cv2.cv.CV_HAAR_SCALE_IMAGE) for (x, y, w, h) in faces: cv2.circle(image, (x+w/2, y+h/2), int((w+h)/3), (255, 255, 255), 1)
if any valid faces are found in image, function will return the list of faces with positions. We draw a white circle around each face and display results.