Как установить opencv pip
Установка 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 и посмотреть версию, чтобы убедиться что установка прошла успешно:
В 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 из исходного кода
Шаг 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 и перейдите в неё
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 будет завершена, вы увидите нечто похожее на то, что показано ниже:
Шаг 4. Компиляция OpenCV
Компиляция может занять какое-то время. Это зависит от конфигурации вашей системы. После завершения вы увидите что-то подобное:
Шаг 5. Установка OpenCV
Когда процесс компиляции завершится, установите OpenCV с командой:
Шаг 6. Версия OpenCV
Чтобы проверить, прошла ли установка OpenCV успешно, введите следующие команды. Вы должны увидеть версию OpenCV:
Заключение
В этой статье мы рассмотрели как выполняется установка OpenCV в Ubuntu 18.04 из репозитория или исходных кодов. Теперь вы знаете как получить самую свежую версию программы. Больше информации по использованию библиотеки доступно на официальном сайте.
pip install OpenCV
by Adrian Rosebrock on September 19, 2018
In this tutorial, you will learn how to pip install OpenCV on Ubuntu, macOS, and the Raspberry Pi.
In previous OpenCV install tutorials I have recommended compiling from source; however, in the past year it has become possible to install OpenCV via pip, Python’s very own package manager.
While installing from source will give you the greatest control over your OpenCV configuration, it’s also the hardest and the most time-consuming.
If you’re looking for the fastest possible way to install OpenCV on your system, you want to use pip to install OpenCV (but there are a few things that may trip you up along the way, so make sure you read the rest of this guide).
2019-11-21 Update: An update has been issued to this blog post due to compatibility issues with OpenCV on the Raspberry Pi 4 running BusterOS using this pip install method. Be sure to find the updates via ctrl + f as you search for “2019-11-21 Update”.
To learn how to pip install OpenCV on your system, just keep reading.
Looking for the source code to this post?
pip install OpenCV
In the remainder of this tutorial, I’ll briefly describe the OpenCV packages you can install via pip, Python’s package manager.
From there, I’ll demonstrate how to pip install OpenCV on Ubuntu, macOS, and the Raspberry Pi.
Finally, I’ll review some common problems you may encounter when using pip to install OpenCV.
I’d like to point out an important caveat to this OpenCV installation method before we begin.
The PyPi/PiWheels hosted versions of OpenCV that we’re discussing today do not include “non-free” algorithms such as SIFT, SURF, and other patented algorithms. This is a great method to install OpenCV if you need a quick environment in which you won’t need to run programs containing the non-free algorithms — if that’s not the case, you’ll need to complete a full compile of OpenCV.
The two pip OpenCV packages: opencv-python and opencv-contrib-python
Before we get started I want to remind you that the methods I’m coming here today are unofficial pre-built OpenCV packages that can be installed via pip — they are not official OpenCV packages released by OpenCV.org.
Just because they are not official packages doesn’t mean you should feel uncomfortable using them, but it’s important for you to understand that they are not endorsed and supported directly by the official OpenCV.org team.
All that said — there are four OpenCV packages that are pip-installable on the PyPI repository:
Again, in the vast majority of situations you will want to install opencv-contrib-python on your system.
You DO NOT want to install both opencv-python and opencv-contrib-python — pick ONE of them.
How to pip install OpenCV on Ubuntu
You have two options to install OpenCV on Ubuntu with pip:
First, install some OpenCV dependencies on Ubuntu
We need to refresh/upgrade the pre-installed packages/libraries with the apt-get package manager:
Followed by installing two required packages:
Next, install pip
If you don’t have pip, you’ll need to obtain it first:
Option A: Install OpenCV to your Ubuntu system with pip
I wouldn’t recommend this method unless you have a particular use case where you don’t want isolated, independent Python environments.
Let’s pip install opencv-contrib-python on our system:
In a matter of seconds, OpenCV is ready to go in your system’s site-packages!
Option B: Install OpenCV on Ubuntu into a virtual environment with pip
There are huge benefits to Python virtual environments.
The main benefit is that you can develop multiple projects on your system with isolated packages (many with version dependencies) without having to muddy the waters of your system. You’re also free to add and remove virtual environments as you go.
Put simply: Python virtual environments are a best practice for Python development. Chances are, you should jump on the bandwagon.
My tools of choice are virtualenv and virtualenvwrapper but you could choose an alternative such as venv or Anaconda (conda for short).
Before we can continue, you first need to add some lines to your
Save the file. Then “source it” in your terminal:
You’ll see some terminal output which sets up virtualenvwrapper. You now have access to new terminal commands:
Let’s create a Python 3 virtual environment for OpenCV called cv:
And now with a magic wand (pip), you can pip install OpenCV in a matter of seconds into your new environment:
How to pip install OpenCV on macOS
MacOS is similar to Ubuntu for pip-installing OpenCV.
Again, you have two options to install OpenCV on macOS with pip:
Install pip
If you don’t have pip, you’ll need to obtain it first:
Option A: Install OpenCV to your macOS system with pip
Why? I actually recommend that you go to the Option B and use a virtual environment.
Okay, well if you insist on installing on your macOS system, then it’s just as easy as pip installing OpenCV via:
In a matter of seconds, OpenCV is ready to go in your system’s site-packages.
Option B: Install OpenCV on macOS into a virtual environment with pip
Just like managing packages is a breeze with pip….
…managing projects and their dependencies is a breeze with virtual environments.
You should use Python virtual environments if you’re serious about computer vision development (or any development for that matter).
Here’s how to install virtualenv and virtualenvwrapper, both of which will live in your system site-packages and manage each project’s virtual environment site-packages:
From there, you need to add the following lines to your
…and append these lines to the end:
Save the file — if you are using nano the keyboard shortcuts are listed at the bottom of the window.
Then “source it” in your terminal:
You’ll see a few lines of terminal output indicating that virtualenvwrapper is set up. You now have access to new terminal commands:
Let’s create a Python 3 virtual environment for OpenCV called cv:
And now, using pip, and with a blink of an eye, you can pip install OpenCV on macOS in a matter of seconds into your new environment:
How to pip install OpenCV on Raspberry Pi
Earlier in this post I mentioned that one of the downsides of installing OpenCV is that you don’t have any control over the compile itself — the binaries are prebuilt for you, which while nice, also means you can’t include any additional optimizations.
For the Raspberry Pi, we’re in luck.
Dave Jones (creator of the picamera Python module) and Ben Nuttall of the Raspberry Pi community-run piwheels.org, a Python package repository providing ARM wheels (i.e., pre-compiled binaries packages) for the Raspberry Pi.
Using PiWheels you’ll be able to pip install OpenCV in a matter of seconds (the same is true for other Python libraries that can take a long time to compile, including NumPy, SciPy, scikit-learn, etc.).
So how do you instruct the pip command to use PiWheels?
The short answer is “Nothing!”
If you’re using Raspbian Stretch you’ll be pleased to know that the pip command will check PiWheels for a pre-compiled binary before it checks PyPI, enabling your Pi to save a bunch of CPU cycles (and you a bunch of install time).
Furthermore, when Ben and Dave put together the OpenCV binary for PiWheels they asked me which instructions they should use — I recommended my optimized OpenCV install for the Raspberry Pi — which is exactly the instructions they followed!
If you end up using pip to install OpenCV on your Raspberry Pi, rest assured, you’re using the optimized version.
Let’s get started learning how to pip install OpenCV on our Raspberry Pi.
Install prerequisites on your Raspberry Pi
The Raspberry Pi requires that you install a few system packages before you get started:
Install pip on your Raspberry Pi
The Python package manager, “pip”, can be obtained via wget:
Now you have two options:
Option A: Install OpenCV to your Raspberry Pi system with pip
I wouldn’t recommend this option if you want to be able to use different versions of OpenCV in isolated environments.
But a lot of people deploy their Raspberry Pis for only one purpose/project and don’t need virtual environments.
That being said, it is quite a mess to clean up if you change your mind later and want to use virtual environments, so I’d recommend skipping this option and following Option B.
To pip install OpenCV on your Raspberry Pi system, be sure to use sudo like this:
2019-11-21 Update: Readers have reported that some versions of OpenCV 4 as installed via pip do not work properly on the Raspberry Pi. You may encounter an «undefined symbol: __atomic_fetch_add8» for libatomic error when you import cv2 from Python if you do not use the specific version of OpenCV mentioned in the code block above.
In a matter of seconds, OpenCV is ready to go in your Raspberry Pi’s site-packages along with any other packages you may have installed.
Option B: Install OpenCV into a virtual environment with pip on your Raspberry Pi
Here’s how to install virtualenv and virtualenvwrapper, the tools I use to get it done:
Then you need to add the following lines to your
Save the file. Then “source it” in your terminal:
Terminal output will be printed indicating that virtualenvwrapper is ready. Be sure to inspect it for errors.
You now have access to new terminal commands:
To create a Python 3 virtual environment which will house OpenCV and other packages you install, simply use mkvirtualenv and the command below:
And now with a flip of the wrist, you can pip install OpenCV into cv :
2019-11-21 Update: Readers have reported that some versions of OpenCV 4 as installed via pip do not work properly on the Raspberry Pi. You may encounter an «undefined symbol: __atomic_fetch_add8» for libatomic error when you import cv2 from Python if you do not use the specific version of OpenCV mentioned in the code block above.
That’s all there is to it with PiWheels!
I bet you’re using the PiCamera as your imaging sensor. You can install the Python module using the following command (just take note of the quotes):
Testing our pip install of OpenCV
Did you know that OpenCV’s 3.3+ has a DNN module which can run Deep Learning models?
You might be surprised, but your version of OpenCV can do this out of the box now, with little to no additional software.
Here’s what you need to install first (assuming a cv virtual environment):
Now double check that you have all software ready by opening a Python shell:
The Raspberry Pi will show a different version of Python 3, which is expected.
Now it’s time to download the code.
Be sure to use the “Downloads” section of this blog post to download the source code + pre-trained MobileNet SSD neural network.
From there, execute the following command:
Figure 1: A short clip of Real-time object detection with deep learning and OpenCV
I’m using a Macbook Pro. A framerate of 6 FPS is pretty good using a CPU on a laptop.
Raspberry Pis are resourced constrained, therefore we can leverage a few tricks to create the illusion of higher FPS. If you’re on the Raspberry Pi, execute the following command:
Here I’ve created the illusion of fast 27 FPS on the Raspberry Pi while the neural network in the background is only capable of processing 0.9 FPS.
How is this possible?
Threading and queues.
It’s a little bit advanced, but if you read the original blog post (for the Raspberry Pi), you’ll understand the process. Plus, you’ll be able to impress your friends and family.
What to look out for when using pip to install OpenCV
To start, not all Python distributions will have a version of OpenCV that is pip-installable.
Newer versions of Python and newer operating systems (and not to mention, older versions which have reached their end of life) may not have a version of OpenCV ready to go in the PyPI repository as the open source community has not had a chance to release such a version yet.
In those situations you can either:
In these scenarios, OpenCV will error out saying that it was not compiled with GTK or QT support.
Third, I know readers have reported issues when executing import cv2 in their terminals, Jupyter Notebooks, or Python shells — this isn’t an issue with the pip install of OpenCV.
In most, but not all, situations, the error is not related to your actual install of OpenCV.
Instead, it’s more likely a problem with your understanding of some combination of:
You’ll want to double-check your commands, repeat the steps, and examine your output closely before reporting an issue importing the cv2 bindings.
Finally, the version of OpenCV that will get installed via pip does not include “non-free” algorithms such as SIFT, SURF, and other patented algorithms. If you don’t need to use patented algorithms, then you’re golden. Otherwise, I recommend that you compile OpenCV from source via one of my installation tutorials for your system.
What’s next? I recommend PyImageSearch University.
I strongly believe that if you had the right teacher you could master computer vision and deep learning.
Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?
That’s not the case.
All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that’s exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.
If you’re serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.
Inside PyImageSearch University you’ll find:
Summary
In today’s tutorial, you learned how to pip install OpenCV on your operating system.
Specifically, we covered how to install OpenCV via pip on Ubuntu, macOS, and Raspberry Pi.
While installing OpenCV via pip may be the easiest method to get you started, keep in mind that you may run into other issues.
If you find yourself running into errors or problems using your pip install of OpenCV, be sure to refer to the “What to look out for when using pip to install OpenCV” section of this blog post.
I hope you enjoyed today’s tutorial!
To be notified when future blog posts are published here on the PyImageSearch blog, be sure to enter your email address in the form below.
Download the Source Code and FREE 17-page Resource Guide
About the Author
Hi there, I’m Adrian Rosebrock, PhD. All too often I see developers, students, and researchers wasting their time, studying the wrong things, and generally struggling to get started with Computer Vision, Deep Learning, and OpenCV. I created this website to show you what I believe is the best possible way to get your start.
Как установить библиотеку OpenCV в Python – 2 способа
OpenCV – это библиотека Python с открытым исходным кодом, которая используется для понимания содержимого цифрового изображения. CV – это аббревиатура компьютерного зрения. Она извлекает описание из изображения в реальном времени или цифрового изображения, которое может быть объектом, текстовым описанием и т. д.
Мы можем выполнять множество задач с помощью библиотеки OpenCV, таких как обнаружение лиц, распознавание лиц, обнаружение blob-объектов, выделение границ, фильтр изображений, сопоставление шаблонов и т.д. Разберем как установить библиотеку OpenCV в нашей среде Python.
Установка OpenCV
OpenCV устанавливается следующими способами:
Использование команды pip
Откройте командную строку и введите следующую команду.
Или можно установить без дополнительного модуля с помощью следующей команды:
Теперь мы проверим правильность установки OpenCV. Импортируйте модуль cv2 и распечатайте его версию.
Если он правильно установлен, то он покажет свою версию.
Использование Anaconda
Anaconda – это программный пакет Python. Anaconda с Jupyter – лучший способ работать с OpenCV. Во-первых, нам нужно установить установщик графики Anaconda с официального сайта.
Теперь выберите подходящий установщик для вашей версии Python.
После завершения загрузки откройте командную строку Anaconda и введите следующую команду.
Затем нажмите кнопку ввода, загрузится всю номинальная конфигурация OpenCV.
opencv-python 4.5.4.60
pip install opencv-python Copy PIP instructions
Released: Nov 22, 2021
Wrapper package for OpenCV python bindings.
Navigation
Project links
Statistics
View statistics for this project via Libraries.io, or by using our public dataset on Google BigQuery
License: MIT License (MIT)
Maintainer: Olli-Pekka Heinisuo
Requires: Python >=3.6
Maintainers
Classifiers
Project description
OpenCV on Wheels
Pre-built CPU-only OpenCV packages for Python.
Check the manual build section if you wish to compile the bindings from source to enable additional modules such as CUDA.
Installation and Usage
If you have previous/other manually installed (= not installed via pip ) version of OpenCV installed (e.g. cv2 module in the root of Python’s site-packages), remove it before installation to avoid conflicts.
Select the correct package for your environment:
There are four different packages (see options 1, 2, 3 and 4 below) and you should SELECT ONLY ONE OF THEM. Do not install multiple different packages in the same environment. There is no plugin architecture: all the packages use the same namespace ( cv2 ). If you installed multiple different packages in the same environment, uninstall them all with pip uninstall and reinstall only one package.
a. Packages for standard desktop environments (Windows, macOS, almost any GNU/Linux distribution)
b. Packages for server (headless) environments (such as Docker, cloud environments etc.), no GUI library dependencies
These packages are smaller than the two other packages above because they do not contain any GUI functionality (not compiled with Qt / other GUI components). This means that the packages avoid a heavy dependency chain to X11 libraries and you will have for example smaller Docker images as a result. You should always use these packages if you do not use cv2.imshow et al. or you are using some other package (such as PyQt) than OpenCV to create your GUI.
Import the package:
All packages contain Haar cascade files. cv2.data.haarcascades can be used as a shortcut to the data folder. For example:
Before opening a new issue, read the FAQ below and have a look at the other issues which are already open.
Frequently Asked Questions
Q: Do I need to install also OpenCV separately?
A: No, the packages are special wheel binary packages and they already contain statically built OpenCV binaries.
A: If the import fails on Windows, make sure you have Visual C++ redistributable 2015 installed. If you are using older Windows version than Windows 10 and latest system updates are not installed, Universal C Runtime might be also required.
Windows N and KN editions do not include Media Feature Pack which is required by OpenCV. If you are using Windows N or KN edition, please install also Windows Media Feature Pack.
If you have Windows Server 2012+, media DLLs are probably missing too; please install the Feature called «Media Foundation» in the Server Manager. Beware, some posts advise to install «Windows Server Essentials Media Pack», but this one requires the «Windows Server Essentials Experience» role, and this role will deeply affect your Windows Server configuration (by enforcing active directory integration etc.); so just installing the «Media Foundation» should be a safer choice.
If the above does not help, check if you are using Anaconda. Old Anaconda versions have a bug which causes the error, see this issue for a manual fix.
If you still encounter the error after you have checked all the previous solutions, download Dependencies and open the cv2.pyd (located usually at C:\Users\username\AppData\Local\Programs\Python\PythonXX\Lib\site-packages\cv2 ) file with it to debug missing DLL issues.
Q: I have some other import errors?
A: Make sure you have removed old manual installations of OpenCV Python bindings (cv2.so or cv2.pyd in site-packages).
Q: Function foo() or method bar() returns wrong result, throws exception or crashes interpreter. What should I do?
A: The repository contains only OpenCV-Python package build scripts, but not OpenCV itself. Python bindings for OpenCV are developed in official OpenCV repository and it’s the best place to report issues. Also please check
Q: Why the packages do not include non-free algorithms?
A: Non-free algorithms such as SURF are not included in these packages because they are patented / non-free and therefore cannot be distributed as built binaries. Note that SIFT is included in the builds due to patent expiration since OpenCV versions 4.3.0 and 3.4.10. See this issue for more info: https://github.com/skvark/opencv-python/issues/126
Q: Why the package and import are different (opencv-python vs. cv2)?
Documentation for opencv-python
The aim of this repository is to provide means to package each new OpenCV release for the most used Python versions and platforms.
CI build process
In Linux and MacOS build: get OpenCV’s optional C dependencies that we compile against
Checkout repository and submodules
Find OpenCV version from the sources
Rearrange OpenCV’s build result, add our custom files and generate wheel
Linux and macOS wheels are transformed with auditwheel and delocate, correspondingly
Install the generated wheel
Test that Python can import the library and run some sanity checks
Use twine to upload the generated wheel to PyPI (only in release builds)
The build can be customized with environment variables. In addition to any variables that OpenCV’s build accepts, we recognize:
See the next section for more info about manual builds outside the CI environment.
Manual builds
If some dependency is not enabled in the pre-built wheels, you can also run the build locally to create a custom wheel.
Manual debug builds
In order to build opencv-python in an unoptimized debug build, you need to side-step the normal process a bit.
If you would like the build produce all compiler commands, then the following combination of flags and environment variables has been tested to work on Linux:
Source distributions
Since OpenCV version 4.3.0, also source distributions are provided in PyPI. This means that if your system is not compatible with any of the wheels in PyPI, pip will attempt to build OpenCV from sources. If you need a OpenCV version which is not available in PyPI as a source distribution, please follow the manual build guidance above instead of this one.
You can also force pip to build the wheels from the source distribution. Some examples:
If you need contrib modules or headless version, just change the package name (step 4 in the previous section is not needed). However, any additional CMake flags can be provided via environment variables as described in step 3 of the manual build section. If none are provided, OpenCV’s CMake scripts will attempt to find and enable any suitable dependencies. Headless distributions have hard coded CMake flags which disable all possible GUI dependencies.
On slow systems such as Raspberry Pi the full build may take several hours. On a 8-core Ryzen 7 3700X the build takes about 6 minutes.
Licensing
Opencv-python package (scripts in this repository) is available under MIT license.
OpenCV itself is available under Apache 2 license.
Third party package licenses are at LICENSE-3RD-PARTY.txt.
All wheels ship with FFmpeg licensed under the LGPLv2.1.
Non-headless Linux wheels ship with Qt 5 licensed under the LGPLv3.
The packages include also other binaries. Full list of licenses can be found from LICENSE-3RD-PARTY.txt.
Versioning
find_version.py script searches for the version information from OpenCV sources and appends also a revision number specific to this repository to the version string. It saves the version information to version.py file under cv2 in addition to some other flags.
Releases
A release is made and uploaded to PyPI when a new tag is pushed to master branch. These tags differentiate packages (this repo might have modifications but OpenCV version stays same) and should be incremented sequentially. In practice, release version numbers look like this:
cv_major.cv_minor.cv_revision.package_revision e.g. 3.1.0.0
The master branch follows OpenCV master branch releases. 3.4 branch follows OpenCV 3.4 bugfix releases.
Development builds
Every commit to the master branch of this repo will be built. Possible build artifacts use local version identifiers:
cv_major.cv_minor.cv_revision+git_hash_of_this_repo e.g. 3.1.0+14a8d39
These artifacts can’t be and will not be uploaded to PyPI.
Manylinux wheels
Linux wheels are built using manylinux2014. These wheels should work out of the box for most of the distros (which use GNU C standard library) out there since they are built against an old version of glibc.
The default manylinux2014 images have been extended with some OpenCV dependencies. See Docker folder for more info.
Supported Python versions
Python 3.x compatible pre-built wheels are provided for the officially supported Python versions (not in EOL):
Backward compatibility
Starting from 4.2.0 and 3.4.9 builds the macOS Travis build environment was updated to XCode 9.4. The change effectively dropped support for older than 10.13 macOS versions.
Project details
Project links
Statistics
View statistics for this project via Libraries.io, or by using our public dataset on Google BigQuery
License: MIT License (MIT)
Maintainer: Olli-Pekka Heinisuo
Requires: Python >=3.6
Maintainers
Classifiers
Download files
Download the file for your platform. If you’re not sure which to choose, learn more about installing packages.