- Электрический блогнот
- мои заметки на полях
- Сборка OpenCV с поддержкой NVIDIA GPU
- NVidia драйвер и библиотеки CUDA
- Шаг 1 — устанавливаем необходимые библиотеки
- CentOS 8
- Ubuntu
- Шаг 2 — устанаваливаем необходимый софт
- cmake
- Python
- устанавливаем дополнительные Python модули
- Шаг 5 — собираем OpenCV из исходников
- Шаг 6 — проверка сборки openCV с GPU
- Express проверка
- OpenCV dnn object detection
- Build OpenCV DNN Module with Nvidia GPU Support on Ubuntu 18.04
- Menu with Compiling OpenCV with CUDA and cuDNN-enabled DNN Module
- Assumptions
- Step #1: Install Nvidia CUDA driver, CUDA toolkit, and cuDNN
- Step #2 Install OpenCV Dependencies
- Step #3 Download OpenCV Source Code
- Step #4 Configure Python Virtual Environment
- Step #5 Determine Your CUDA Architecture Version
- Step #6 Configure OpenCV with Nvidia GPU Support
- Step #7 Compile OpenCV
- Step #8 Install OpenCV with CUDA DNN Module
- Verify the Installation
- Steps to Verify, C++ Part
- Python
- Steps to Verify, Python Part
- Recap
- Special Thanks
- Cuda Chen’s Blog
Электрический блогнот
мои заметки на полях
Сборка OpenCV с поддержкой NVIDIA GPU
Использование нейронных сетей (да, сейчас это модно) дает дополнительные возможности в области безопасности, а имнно в охранных системах видеонаблюдения. Имея хороший процессор или мощную видеокарту, вы, фактически на лету можете анализировать видеопоток с камер, классифицируя (classification) или находя необходимые объекты (object detection) в кадре. Последующий детальный анализ таких кадров трудно переоценить.
Есть два популярных способа запустить нейросетку:
1) используя родной «движок» на котором эта сеть и была обучена (например установить в систему библиотеки Tensorflow);
2) взять «движок» стороннего производителя, который понимает такую нейросеть и умеет пропускать изображения через нее.
В этой статье мы будем собирать из исходников «движок» типа 2, от стороннего производителя, а именно OpenCV. Этот пакет умеет работать со многими типами нейронных сетей использую модуль «Deep Neural Network» (dnn), а с недавнего времени dnn научился запускать их и на GPU.
Нейросеть лучше запускать на графическом ускорителе (gpu). Именно графические ускорители Nvidia с технологией CUDA, дают значительное ускорение при работе нейросетей. Поэтому пакет OpenCV мы будем компилировать с поддержкой GPU.
Собирать будем под Linux. Неважно какой LInux. Можно Ubuntu, можно CentOS. Разницы нет никакой, кроме начального этапа. Инструкция универсальная и привязка к дистрибутиву сведена к минимуму.
При установке будем придерживаться следующих принципов:
- Как можно меньше использовать учетную запись «root» (только для установки самых необходимых библиотек).
- Ставить все в домашнюю директорию и ничего «не размазывать по системе».
- Придерживаться принципа «все свое ношу с собой», для этого в домашней директории создадим папку, например «system» и все будем складывать в нее.
NVidia драйвер и библиотеки CUDA
Перед тем, как приступить к сборке OpenCV необходимо, чтобы в вашей системе були установлены:
- Драйвер NVidia (гуглите как это делается именно для вашей конкретной системы).
- Библиотеки CUDA (вот здесь я подробно и с картиками рассказал, как это сделать.
Шаг 1 — устанавливаем необходимые библиотеки
Это очень важный шаг. Если на этом этапе не установить какую-то библиотеку, то сборщик OpenCV отметит для себя, что ее нет в системе и продолжит сборку дальше, а именно без этой фичи. А вы потом ищите, почему, например не работает экспорт в jpg. А все потому что libjpeg не был установлен и сборщик пропустил его. Лучше сразу все поставить, чтобы потом не бегать по stackoverflow с вопросами.
CentOS 8
Ubuntu
Библиотеки установлены. Все последующие шаги не будут зависить от конкретного дистрибутива Linux. Поэтому инструкции подойдут, как Ubuntu, так и любому другому Linux.
Шаг 2 — устанаваливаем необходимый софт
Для сборки opencv потребуется установить некоторый софт. Скорей всего это уже установлено на вашем компьютере, но непонятно какой версии. Поэтому лучше собрать все из исходников. Для этого создаем в домашней директории папку «system»:
В этой папке будут установлены вспомогательные программы и сама библиотека opencv.
cmake
Для сборки opencv требуется cmake причем довольно свежий. Качаем из официального репо и распаковываем в
Сразу же добавляем cmake в путь для поиска:
Python
Если вас устраивает Python, установленный в вашей системе, то этот шаг можете пропустить. Я предпочитаю собирать Python из исходников (делается это быстро). Устанавливать все необходимые пакеты и пользоваться ужеэтой сборкой. Можно использовать еще Anaconda, но это кому как нравится.
Собираем Python из исходников:
устанавливаем дополнительные Python модули
Шаг 5 — собираем OpenCV из исходников
Скачиваем свежую релизную версию с github:
Создаем скрипт для сборки:
build.sh
Редактируем build.sh и вставляем туда следующий код:
Это очень важный файл. Любая ошибка допущенная в нем сложно потом отлавливается. Поэтому проверьте все пути.
После того, как скрипт отработает появится следующий output.
Если сконфигурировали правильно, то должно быть как в зеленой рамочке.
Ну а дальше классическое:
Крайне рекомендую использовать мультипроцессорность при сборке (-j[кол-во ядер]). Сборка проходит очень медленно. На старом 4-х ядерном Intel i3 OpenCV собирался всю ночь.
После установки обязательно проверяем OpenCV Python модуль:
Настраиваем environment, добавляем следующие строки в
Шаг 6 — проверка сборки openCV с GPU
Express проверка
cv2.cuda.getCudaEnabledDeviceCount() — количество видеокарт доступных OpenCV;
cv2.__version__ — установленная версия OpenCV.
OpenCV dnn object detection
Реальный (боевой) пример использования OpenCV dnn библиотеки для запуска предобученной нейросети на Python.
За основу взят вот этот пример.
Я его слегка модифицировал для задействования gpu.
Скачиваем пример.
Распаковываем и запускаем:
Для мониторинга нагрузки GPU запускаем еще одну терминалку и в ней:
Источник
Build OpenCV DNN Module with Nvidia GPU Support on Ubuntu 18.04
In 2017, OpenCV 3.3 brought a revolutionary DNN module. As time passes, it currently supports plenty of deep learning framework such as TensorFlow, Caffe, and Darknet, etc. With the help of this module, we can use OpenCV to:
- Load a pre-trained model from disk.
- Making a preprocessing to an input image.
- Pass the image through the network and obtain the output results.
- Least dependency (only OpenCV !).
Although we cannot train a deep learning models with OpenCV (this does not make sense, though), we can take the models trained by other deep learning frameworks and perform inference using OpenCV with incredible speed on CPU.
However, the DNN module does not support Nvidia GPU until now. In Google Summer of Code (GSoC) 2019, OpenCV DNN module finally supports Nvidia GPU for inference with the work of Davis King – the creator of dlib – and Yashas Samaga, and this work was made in public in version 4.2.0. As a programmer expertised with OpenCV, I think I should share this exciting news in the first moment. Besides, I will teach you how to compile and install OpenCV with the utility of Nvidia GPU for deep neural network inference, and I will provide the minimal workable example code in both C++ and Python.
Menu with Compiling OpenCV with CUDA and cuDNN-enabled DNN Module
Assumptions
I assume you are using the following settings:
- A Nvidia GPU (of course!).
- Ubuntu 18.04 (or other equivalent Debian-based distro).
- CUDA 10.0 and corresponding version of cuDNN (in here I use v7.6.5).
- Your system account has sudo privilege.
- OpenCV version 4.2.0.
Step #1: Install Nvidia CUDA driver, CUDA toolkit, and cuDNN
- Backup your system, period. To my experience, you may accidently break the system when installing any kind of driver. Although you can recover the system doing the installation backwards, sometimes you just can’t recover successfully because you forget the steps or even the driver does some changes and you don’t notice at all. As a person who broke the system twice (both with install CUDA drivers), I strongly suggest you backup your system in any condition.
- Pre-installation Actions I make some outlines here. For detailed information you can visit here.
- lspci | grep -i nvidia : verify you have a CUDA-capable GPU.
- uname -m && cat /etc/*release : verify you have a supported version of Linux.
- gcc —version : verify the system has GCC installed.
- If not, install GCC by sudo apt-get update && sudo apt-get upgrade && sudo apt-get install build-essential .
- uname -r : check the system has the correct kernel headers and development packages installed.
- sudo apt-get install linux-headers-$(uname -r) : install the kernel headers and development packages of current running kernel.
- Install CUDA driver Install CUDA driver by typing the following commands:
After the installation, reboot the system:
Once your system brings up, type nvidia-smi and it should give a similar output:
- Install CUDA toolkit I will choose runfile packages to install CUDA drivers because you may upgrade the packages if you install with distribution-specific packages methods, which will cause huge problem afterwards.
First, download the runfile suitable of your system from here.
Then type the following command to run the runfile: sudo sh cuda_ _linux.run —override
After finishing the installation, update your bash profile (
/.bashrc ) by insert the following lines at the bottom of the profile:
Then source the profile:
Type nvcc -V . It you get the similar output, you’re done!
- Install cuDNN Installing cuDNN is much less tedious than CUDA driver and CUDA toolkit.
In the beginning, download cuDNN v7.6.5 for CUDA 10.0 from here (you may need to login or signup to download cuDNN).
Next, extract the zip file and put the headers and shared libraries:
If you are here and do not encounter any problem, Congrats! You have finish the hardest part!
Step #2 Install OpenCV Dependencies
OpenCV has a huge of dependencies, and I write in here so that you just copy and past the following command:
Step #3 Download OpenCV Source Code
Currently there is no python wheels or dpkg packages that built with Nvidia GPU support. So we have to compile OpenCV from source.
In this tutorial, I put both opencv and opencv_contrib repository in
/opencv directory. I will use git to download the source code so that I can change the version I like:
Step #4 Configure Python Virtual Environment
For developping with Python, it is a good practice to use virtual environment due to using different versions of Python libraries in isolation and causing less problem in production environment.
In this part, I will use virtualenv and virtualenvwrapper as the virtual environment.
- Install virtualenv and virtualenvwrapper using pip .
After installing these two packages, you need to add these lines in
/.bashrc in order to let bash load virtualenv and virtualenvwrapper each time when terminal is up:
Then reload you
/.bashrc to let the settings activate immediately:
- Create a virtual environment. The first step is to create the virtual environment:
This command will create a virtual environment called opencv_cuda with Python 3. After the creation, your current working virtual environment should be opencv_cuda .
NOTE: If you ever close your terminal or deactivate the virtual environment, you can re-activate it by typing:
Because OpenCV Python will use numpy , we then install numpy :
Step #5 Determine Your CUDA Architecture Version
As a experienced CUDA programmer, determining the CUDA architecture version is a required practice because it lets the compiler generate more efficient code on your GPU. Furthermore, setting architecture params which does not include the architecture of your Nvidia GPU will let your program not working while executing.
We can use nvidia-smi to figure out what model of your Nvidia GPU is:
You can see that I am using an Nvidia Geforce GTX 1080 GPU written in the Name section. Please make sure you have verfied your GPU model by running nvidia-smi before you continue the next part.
After you get the model of Nvidia GPU, you can find your CUDA Architecture using this page:
Scroll down to the Paragraph of “Your GPU Compute Capability”. As I’m using GTX 1080, I will click on the “CUDA-Enabled GeForce and TITAN Products” sections.
After examining it, I realize my Nvidia GPU architecture version is 6.1 . As a reminder, your GPU architecture version may vary.
Once you got the GPU architecture version, leave a note of it because we will use it on the next step.
Step #6 Configure OpenCV with Nvidia GPU Support
OpenCV uses CMake to configure and generate the build. First of all activate the opencv_cuda virtual environment:
Then, change directory to the location you cloned the OpenCV source code (e.g.,
/opencv , and then create a build directory (we use out-of-source building):
Next, run the following cmake command, and change the CUDA_ARCH_BIN variable you wrote down in step #5:
For one more point, check the install path in Python 3 section of CMake output. We will use install path in step #8. So please leave a note of install path .
Step #7 Compile OpenCV
If cmake exited with no errors, you then compile OpenCV with the following command:
Step #8 Install OpenCV with CUDA DNN Module
If make completed in success, you the type the following commands to install OpenCV:
Then, we are going to create a sym-link the OpenCV Python bindings into your Python virtual environment. Mentioned in Step #6, we know that the install path is /usr/local/lib/python3.6/site-packages/cv2/python-3.6 .
To confirm, you can use the ls command:
You can see the name of my OpenCV Python bindings is cv2.cpython-36m-x86_64-linux-gnu.so (you may have the similar name of your own built bindings).
Next, create a sym-link to your virtual environment:
Commented by @ymh66, here should be
Thanks for @ymh66 correct this typo!
Remember to take a second to check your file paths because ln will slient fail if the path of OpenCV bindings are not correct.
Verify the Installation
We can verify the installation is successful with two means:
- The program compiles with OpenCV in no problem.
- The program executes with no errors.
Steps to Verify, C++ Part
- Download the repo and the weights mentioned in README.
- Go to cpp_code directory and type this command: g++ -o opencv_dnn_cuda_test_cpp main.cpp -I/usr/local/include/opencv4 -lopencv_core -lopencv_dnn -lopencv_highgui -lopencv_imgcodecs
- Run the executable by using this command: opencv_dnn_cuda_test_cpp
- If terminal outputs similar message, you’re done!
Python
We can verify the installation is successful with two means:
- We can import OpenCV in Python script.
- We are able to use Nvidia GPU via the DNN module.
Steps to Verify, Python Part
- Download the repo and the weights mentioned in README.
- Activate the virtual environment (that is, opencv_cuda ).
- Go to python_code directory and type the command: python main.py
- If terminal outputs similar message, you’re done!
Recap
In this post, I teach you how to install OpenCV with CUDA-enabled DNN modules from scratch on Ubuntu 18.04. Also, I provided a minimal sample code both in C++ and Python so that you can adapt them in the later projects for your convenience.
To use CUDA as the backend of OpenCV DNN module, you can simply add these two lines after you load the pre-trained model:
Special Thanks
I would like to give a big gratitude to this post on pyimagesearch.com. Without this post, I would not complete this post in simplicity.
I would also like to give specia thanks to YashasSamaga, the main contributor of OpenCV DNN module with CUDA. He also teaches a lot in the issues on OpenCV GitHub repo which helps plenty of people to solve the problems of compilation with OpenCV CUDA-enabled DNN modules.
Cuda Chen’s Blog
Image Processing, Machine Learning, Parallel Computing, video games, and living.
Источник