Opencv python module install

Установка OpenCV-Python на виртуальной среде для суперчайников

Здесь вы найдете пошаговый пример установки библиотеки OpenCV на Python.

  • Установка Python
  • Установка виртуальной среды
  • Установка OpenCV + jupiterlab, numpy, matplotlib
  • Тестирование

Все тестировала на планшете Microsoft Surface, Windows 10 Pro, c 64-битной операционной системой.

Предположим, что на вашем устройстве ничего не установлено заранее.

  1. Сначала установим Python.
    Скачиваем нужную версию и запускаем .exe файл. Не забываем установить галочку add path. Я установила Python 3.7.3 от 25 марта 2019 г., потому что новая на данный момент версия Python 3.7.4 от 8го июля 2019 г. работала некорректно, а именно в терминале некоторые команды зависали. Открываем командную строку.
  2. Устанавливаем virtualenv.
    Виртуальная среда нам нужна для того, чтобы для каждого отдельного проекта была своя «комната» со своими версиями установленных библиотек, которые не будут зависеть от других проектов и путаться между собой.
    Пакеты будем устанавливать с помощью pip. Он в последнее время сразу идет с Python, но обычно требуется его обновить командой:
    python -m pip install —upgrade pip
    Обновили pip, теперь установим виртуальную среду:
    pip install virtualenv
    Командой cd перейдите в папку, в которой хотите создать среду и введите команду:
    mkdir opencvtutorial_env — так мы создали среду с названием opencvtutorial_env.
    Далее вводим команду virtualenv opencvtutorial_env и для активации перейдите в папку среды и далее с помощью Tab до activate.
    .\opencvtutorial_env\Scripts\activate
  3. Установим библиотеки OpenCV-Python, Numpy и Matplotlib, которые понадобятся для тестирования функций opencv.
    Самый легкий и быстрый вариант установки у меня получился с неофициальной версии. Устанавливаем его командой:
    pip install opencv-python
    Вместе с opencv-python в подарок с этим пакетом идет numpy. Дополнительно установим matplotlib: pip install matplotlib .
  4. Установим pip install jupyterlab и запустим его командой jupyter notebook .
    Теперь осталось проверить все ли у нас работает. В открывшемся окне создаем новый Python 3 файл, и запускаем команду:
    import cv2 as cv
    print( cv.__version__ )
    Если выходит версия opencv, то поздравляю, можно тестировать туториалы c официального сайта. Мои примеры работ по туториалам можно найти здесь.
Читайте также:  Единицы измерения

Источник

Opencv python module install

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 python3-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.

Источник

Install OpenCV-Python in Windows¶

1.1. Python-2.7.x. 1.2. Numpy. 1.3. Matplotlib (Matplotlib is optional, but recommended since we use it a lot in our tutorials).

>>> import cv2 >>> print cv2.__version__ 

If the results are printed out without any errors, congratulations . You have installed OpenCV-Python successfully.

Building OpenCV from source¶

2.1. Python 2.7.x 2.2. Numpy 2.3. Matplotlib (Matplotlib is optional, but recommended since we use it a lot in our tutorials.)

In this case, we are using 32-bit binaries of Python packages. But if you want to use OpenCV for x64, 64-bit binaries of Python packages are to be installed. Problem is that, there is no official 64-bit binaries of Numpy. You have to build it on your own. For that, you have to use the same compiler used to build Python. When you start Python IDLE, it shows the compiler details. You can get more information here. So your system must have the same Visual Studio version and build Numpy from source.

Another method to have 64-bit Python packages is to use ready-made Python distributions from third-parties like Anaconda, Enthought etc. It will be bigger in size, but will have everything you need. Everything in a single shell. You can also download 32-bit versions also.

  1. Make sure Python and Numpy are working fine.
  2. Download OpenCV source. It can be from Sourceforge (for official release version) or from Github (for latest source).
  3. Extract it to a folder, opencv and create a new folder build in it.
  4. Open CMake-gui (Start > All Programs > CMake-gui)
  5. Fill the fields as follows (see the image below):

7.1. Click on Browse Source. and locate the opencv folder. 7.2. Click on Browse Build. and locate the build folder we created. 7.3. Click on Configure.

capture1

7.4. It will open a new window to select the compiler. Choose appropriate compiler (here, Visual Studio 11) and click Finish.

capture2

capture3

capture5

  • Remaining fields specify what modules are to be built. Since GPU modules are not yet supported by OpenCV-Python, you can completely avoid it to save time (But if you work with them, keep it there). See the image below: capture6
  • Now click on ENABLE field to expand it. Make sure ENABLE_SOLUTION_FOLDERS is unchecked (Solution folders are not supported by Visual Studio Express edition). See the image below: capture7
  • Also make sure that in the PYTHON field, everything is filled. (Ignore PYTHON_DEBUG_LIBRARY). See image below: capture80
  • Finally click the Generate button.
  • Now go to our opencv/build folder. There you will find OpenCV.sln file. Open it with Visual Studio.
  • Check build mode as Release instead of Debug.
  • In the solution explorer, right-click on the Solution (or ALL_BUILD) and build it. It will take some time to finish.
  • Again, right-click on INSTALL and build it. Now OpenCV-Python will be installed. capture8
  • Open Python IDLE and enter import cv2 . If no error, it is installed correctly.
  • We have installed with no other support like TBB, Eigen, Qt, Documentation etc. It would be difficult to explain it here. A more detailed video will be added soon or you can just hack around.

    Источник

    Оцените статью