Установка OpenCV в Ubuntu 18.04
OpenCV (Open Source Computer Vision Library) – библиотека компьютерного зрения выпущенная под лицензией BSD, свободная как для личного, так и коммерческого использования. У неё есть интерфейсы для C++, Python и Java, поддерживается Windows, Linux, MacOS, IOS и Android. Эта библиотека используется для анализа видео и изображений.
OpenCV имеет модульную структуру, а это значит что пакет состоит из нескольких статических и динамических библиотек. В этой статье мы рассмотрим как выполняется установка OpenCV на Ubuntu 18.04 из официального репозитория или исходников.
Установка OpenCV из репозитория Ubuntu
Пакет OpenCV доступен в официальных репозиториях Ubuntu 18.04. На данный момент в репозиториях находится версия 3.2, а на официальном сайте уже можно найти версию 4.0. Чтобы установить OpenCV в Ubuntu 18.04 вместе с Python 3, выполните:
sudo apt update
sudo apt install python3-opencv
Затем нужно импортировать модуль cv2 в интерпретаторе python и посмотреть версию, чтобы убедиться что установка прошла успешно:
python3 -c «\
import cv2
print(cv2.__version__)»
В Ubuntu 18.04 LTS по умолчанию версия Python – 3.6. Если нужно установить OpenCV с привязками Python 2, загрузите пакет python-opencv.
Установка OpenCV с помощью PIP
Пакетный менеджер pip позволяет устанавливать различные пакеты python в систему. Сначала надо установить сам пакетный менеджер:
sudo apt install python-pip
Затем остается установить саму библиотеку:
sudo pip install opencv-python
После этого вы можете проверить версию библиотеки как описано в предыдущем пункте.
Установка OpenCV из исходного кода
В официальном репозитории и репозитории pip находится не самая новая версия. На момент написания статьи, самая новая версия — 4.1.0. Если вы хотите установить именно её, вам понадобиться компилировать OpenCV из исходного кода.
Шаг 1. Установка зависимостей
Сначала установим зависимости:
sudo apt install build-essential cmake git pkg-config libgtk-3-dev libavcodec-dev libavformat-dev libswscale-dev libv4l-dev libxvidcore-dev libx264-dev libjpeg-dev libpng-dev libtiff-dev gfortran openexr libatlas-base-dev python3-dev python3-numpy libtbb2 libtbb-dev libdc1394-22-dev
Шаг 2. Клонирование репозитория
Создайте директорию в которую будут сохранены репозитории OpenCV и перейдите в неё
Затем скачайте репозитории. Будут загружены два репозитория — opencv и opencv-contrib. Второй репозиторий содержит алгоритмы компьютерного зрения и будет полезен всем, кто хочет работать с этой технологией.
git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git
Если вы хотите установить старую версию OpenCV перейдите в каталог обоих репозиториев и выполните в них команду:
Шаг 3. Подготовка к сборке
Когда загрузка завершится, создайте временную директорию сборки и переключитесь на нее:
/opencv_build/opencv
mkdir build
cd build
Подготовьте сборку OpenCV, используя CMake:
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_C_EXAMPLES=ON \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D OPENCV_GENERATE_PKGCONFIG=ON \
-D OPENCV_EXTRA_MODULES_PATH=
/opencv_build/opencv_contrib/modules \
-D BUILD_EXAMPLES=ON ..
Как только сборка CMake будет завершена, вы увидите нечто похожее на то, что показано ниже:
Шаг 4. Компиляция OpenCV
Измените флаг -j в соответствии с вашим процессором. Узнать число ядер процессора можно командой nproc. Например, в системе 4 ядра, поэтому используется флаг –j4. Начните процесс компиляции:
Компиляция может занять какое-то время. Это зависит от конфигурации вашей системы. После завершения вы увидите что-то подобное:
Шаг 5. Установка OpenCV
Когда процесс компиляции завершится, установите OpenCV с командой:
Шаг 6. Версия OpenCV
Чтобы проверить, прошла ли установка OpenCV успешно, введите следующие команды. Вы должны увидеть версию OpenCV:
pkg-config —modversion opencv4
python3 -c «\
import cv2
print(cv2.__version__)»
Заключение
В этой статье мы рассмотрели как выполняется установка OpenCV в Ubuntu 18.04 из репозитория или исходных кодов. Теперь вы знаете как получить самую свежую версию программы. Больше информации по использованию библиотеки доступно на официальном сайте.
Opencv install python linux
In this tutorial We will learn to setup OpenCV-Python in Ubuntu System. Below steps are tested for Ubuntu 16.04 and 18.04 (both 64-bit).
OpenCV-Python can be installed in Ubuntu in two ways:
- Install from pre-built binaries available in Ubuntu repositories
- Compile from the source. In this section, we will see both.
Another important thing is the additional libraries required. OpenCV-Python requires only Numpy (in addition to other dependencies, which we will see later). But in this tutorials, we also use Matplotlib for some easy and nice plotting purposes (which I feel much better compared to OpenCV). Matplotlib is optional, but highly recommended. Similarly we will also see IPython, an Interactive Python Terminal, which is also highly recommended.
Installing OpenCV-Python from Pre-built Binaries
This method serves best when using just for programming and developing OpenCV applications.
Install package python-opencv with following command in terminal (as root user).
Open Python IDLE (or IPython) and type following codes in Python terminal.
If the results are printed out without any errors, congratulations . You have installed OpenCV-Python successfully.
It is quite easy. But there is a problem with this. Apt repositories may not contain the latest version of OpenCV always. For example, at the time of writing this tutorial, apt repository contains 2.4.8 while latest OpenCV version is 3.x. With respect to Python API, latest version will always contain much better support and latest bug fixes.
So for getting latest source codes preference is next method, i.e. compiling from source. Also at some point in time, if you want to contribute to OpenCV, you will need this.
Building OpenCV from source
Compiling from source may seem a little complicated at first, but once you succeeded in it, there is nothing complicated.
First we will install some dependencies. Some are required, some are optional. You can skip optional dependencies if you don’t want.
Required build dependencies
We need CMake to configure the installation, GCC for compilation, Python-devel and Numpy for building Python bindings etc.
Opencv install python linux
In this tutorial We will learn to setup OpenCV-Python in Ubuntu System. Below steps are tested for Ubuntu 16.04 and 18.04 (both 64-bit).
OpenCV-Python can be installed in Ubuntu in two ways:
- Install from pre-built binaries available in Ubuntu repositories
- Compile from the source. In this section, we will see both.
Another important thing is the additional libraries required. OpenCV-Python requires only Numpy (in addition to other dependencies, which we will see later). But in this tutorials, we also use Matplotlib for some easy and nice plotting purposes (which I feel much better compared to OpenCV). Matplotlib is optional, but highly recommended. Similarly we will also see IPython, an Interactive Python Terminal, which is also highly recommended.
Installing OpenCV-Python from Pre-built Binaries
This method serves best when using just for programming and developing OpenCV applications.
Install package python-opencv with following command in terminal (as root user).
Open Python IDLE (or IPython) and type following codes in Python terminal.
If the results are printed out without any errors, congratulations . You have installed OpenCV-Python successfully.
It is quite easy. But there is a problem with this. Apt repositories may not contain the latest version of OpenCV always. For example, at the time of writing this tutorial, apt repository contains 2.4.8 while latest OpenCV version is 3.x. With respect to Python API, latest version will always contain much better support and latest bug fixes.
So for getting latest source codes preference is next method, i.e. compiling from source. Also at some point in time, if you want to contribute to OpenCV, you will need this.
Building OpenCV from source
Compiling from source may seem a little complicated at first, but once you succeeded in it, there is nothing complicated.
First we will install some dependencies. Some are required, some are optional. You can skip optional dependencies if you don’t want.
Required build dependencies
We need CMake to configure the installation, GCC for compilation, Python-devel and Numpy for building Python bindings etc.
Opencv install python linux
- set full path to OpenCV source code, e.g. /home/user/opencv
- set full path to , e.g. /home/user/opencv/build
- set optional parameters
- run: “Configure”
- run: “Generate”
Note Use cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local .. , without spaces after -D if the above example doesn’t work.
- build type: CMAKE_BUILD_TYPE=Release\Debug
- to build with modules from opencv_contrib set OPENCV_EXTRA_MODULES_PATH to
- set BUILD_DOCS for building documents
- set BUILD_EXAMPLES to build all examples
- PYTHON2(3)_EXECUTABLE =
Build. From build directory execute make, it is recommended to do this in several threads
[optional] Building documents. Enter and run make with target «doxygen»