OpenCV в Python. Часть 1
Привет, Хабр! Запускаю цикл статей по библиотеке OpenCV в Python. Кому интересно, добро пожаловать под кат!
Введение
OpenCV — это open source библиотека компьютерного зрения, которая предназначена для анализа, классификации и обработки изображений. Широко используется в таких языках как C, C++, Python и Java.
Установка
Будем считать, что Python и библиотека OpenCV у вас уже установлены, если нет, то вот инструкция для установки python на windows и на ubuntu, установка OpenCV на windows и на ubuntu.
Немного про пиксели и цветовые пространства
Перед тем как перейти к практике, нам нужно разобраться немного с теорией. Каждое изображение состоит из набора пикселей. Пиксель — это строительный блок изображения. Если представить изображение в виде сетки, то каждый квадрат в сетке содержит один пиксель, где точке с координатой ( 0, 0 ) соответствует верхний левый угол изображения. К примеру, представим, что у нас есть изображение с разрешением 400×300 пикселей. Это означает, что наша сетка состоит из 400 строк и 300 столбцов. В совокупности в нашем изображении есть 400*300 = 120000 пикселей.
В большинстве изображений пиксели представлены двумя способами: в оттенках серого и в цветовом пространстве RGB. В изображениях в оттенках серого каждый пиксель имеет значение между 0 и 255, где 0 соответствует чёрному, а 255 соответствует белому. А значения между 0 и 255 принимают различные оттенки серого, где значения ближе к 0 более тёмные, а значения ближе к 255 более светлые:
Цветные пиксели обычно представлены в цветовом пространстве RGB(red, green, blue — красный, зелёный, синий), где одно значение для красной компоненты, одно для зелёной и одно для синей. Каждая из трёх компонент представлена целым числом в диапазоне от 0 до 255 включительно, которое указывает как «много» цвета содержится. Исходя из того, что каждая компонента представлена в диапазоне [0,255], то для того, чтобы представить насыщенность каждого цвета, нам будет достаточно 8-битного целого беззнакового числа. Затем мы объединяем значения всех трёх компонент в кортеж вида (красный, зеленый, синий). К примеру, чтобы получить белый цвет, каждая из компонент должна равняться 255: (255, 255, 255). Тогда, чтобы получить чёрный цвет, каждая из компонент должна быть равной 0: (0, 0, 0). Ниже приведены распространённые цвета, представленные в виде RGB кортежей:
Импорт библиотеки OpenCV
Теперь перейдём к практической части. Первое, что нам необходимо сделать — это импортировать библиотеку. Есть несколько путей импорта, самый распространённый — это использовать выражение:
Также можно встретить следующую конструкцию для импорта данной библиотеки:
Загрузка, отображение и сохранение изображения
Для загрузки изображения мы используем функцию cv2.imread(), где первым аргументом указывается путь к изображению, а вторым аргументом, который является необязательным, мы указываем, в каком цветовом пространстве мы хотим считать наше изображение. Чтобы считать изображение в RGB — cv2.IMREAD_COLOR, в оттенках серого — cv2.IMREAD_GRAYSCALE. По умолчанию данный аргумент принимает значение cv2.IMREAD_COLOR. Данная функция возвращает 2D (для изображения в оттенках серого) либо 3D (для цветного изображения) массив NumPy. Форма массива для цветного изображения: высота x ширина x 3, где 3 — это байты, по одному байту на каждую из компонент. В изображениях в оттенках серого всё немного проще: высота x ширина.
С помощью функции cv2.imshow() мы отображаем изображение на нашем экране. В качестве первого аргумента мы передаём функции название нашего окна, а вторым аргументом изображение, которое мы загрузили с диска, однако, если мы далее не укажем функцию cv2.waitKey(), то изображение моментально закроется. Данная функция останавливает выполнение программы до нажатия клавиши, которую нужно передать первым аргументом. Для того, чтобы любая клавиша была засчитана передаётся 0. Слева представлено изображение в оттенках серого, а справа в формате RGB:
И, наконец, с помощью функции cv2.imwrite() записываем изображение в файл в формате jpg(данная библиотека поддерживает все популярные форматы изображений:png, tiff,jpeg,bmp и т. д., поэтому можно было сохранить наше изображение в любом из этих форматов), где первым аргументом передаётся непосредственно само название и расширение, а следующим параметром изображение, которое мы хотим сохранить.
Доступ к пикселям и манипулирование ими
Для того, чтобы узнать высоту, ширину и количество каналов у изображения можно использовать атрибут shape:
Важно помнить, что у изображений в оттенках серого img.shape[2] будет недоступно, так как данные изображения представлены в виде 2D массива.
Чтобы получить доступ к значению пикселя, нам просто нужно указать координаты x и y пикселя, который нас интересует. Также важно помнить, что библиотека OpenCV хранит каналы формата RGB в обратном порядке, в то время как мы думаем в терминах красного, зеленого и синего, то OpenCV хранит их в порядке синего, зеленого и красного цветов:
Cначала мы берём пиксель, который расположен в точке (0,0). Данный пиксель, да и любой другой пиксель, представлены в виде кортежа. Заметьте, что название переменных расположены в порядке b, g и r. В следующей строке выводим значение каждого канала на экран. Как можно увидеть, доступ к значениям пикселей довольно прост, также просто можно и манипулировать значениями пикселей:
В первой строке мы устанавливаем значение пикселя (0, 0) равным (255, 0, 0), затем мы снова берём значение данного пикселя и выводим его на экран, в результате мне на консоль вывелось следующее:
На этом у нас конец первой части. Если вдруг кому-то нужен исходный код и картинка, то вот ссылка на github. Всем спасибо за внимание!
Источник
Opencv with python linux
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.
Make sure that your pip version is up-to-date (19.3 is the minimum supported version): pip install —upgrade pip . Check version with pip -V . For example Linux distributions ship usually with very old pip versions which cause a lot of unexpected problems especially with the manylinux format.
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)
- Option 1 — Main modules package: pip install opencv-python
- Option 2 — Full package (contains both main modules and contrib/extra modules): pip install opencv-contrib-python (check contrib/extra modules listing from OpenCV documentation)
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.
- Option 3 — Headless main modules package: pip install opencv-python-headless
- Option 4 — Headless full package (contains both main modules and contrib/extra modules): pip install opencv-contrib-python-headless (check contrib/extra modules listing from OpenCV documentation)
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.
Q: Pip install fails with ModuleNotFoundError: No module named ‘skbuild’ ?
Since opencv-python version 4.3.0.*, manylinux1 wheels were replaced by manylinux2014 wheels. If your pip is too old, it will try to use the new source distribution introduced in 4.3.0.38 to manually build OpenCV because it does not know how to install manylinux2014 wheels. However, source build will also fail because of too old pip because it does not understand build dependencies in pyproject.toml . To use the new manylinux2014 pre-built wheels (or to build from source), your pip version must be >= 19.3. Please upgrade pip with pip install —upgrade pip .
Q: Import fails on Windows: ImportError: DLL load failed: The specified module could not be found. ?
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 interpriter. 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)? A: It’s easier for users to understand opencv-python than cv2 and it makes it easier to find the package with search engines. cv2 (old interface in old OpenCV versions was named as cv ) is the name that OpenCV developers chose when they created the binding generators. This is kept as the import name to be consistent with different kind of tutorials around the internet. Changing the import name or behaviour would be also confusing to experienced users who are accustomed to the import 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 The project is structured like a normal Python package with a standard setup.py file. The build process for a single entry in the build matrices is as follows (see for example .github/workflows/build_wheels_linux.yml file): 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) Steps 1—4 are handled by pip wheel . 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. 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: 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. 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. 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. 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. 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. 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): 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. Starting from 4.3.0 and 3.4.10 builds the Linux build environment was updated from manylinux1 to manylinux2014 . This dropped support for old Linux distributions. Automated CI toolchain to produce precompiled opencv-python, opencv-python-headless, opencv-contrib-python and opencv-contrib-python-headless packages. Источник
About