Как установить opencv на windows 10

Время на прочтение7 мин

Количество просмотров41K

Введение

В данной статье речь пойдет о сборке и установке OpenCV 4 для C/C++, Python 2 и Python 3 из исходных файлов с дополнительными модулями CUDA 10 на ОС Windows.

Я постарался включить сюда все тонкости и нюансы, с которыми можно столкнуться в ходе установки, и про которые не написано в официальном мануале.

Сборка тестировалась для:

  • Windows 8.1 + Visual Studio 2017 + Python 2/3 + CUDA 10.0 + GeForce 840m
  • Windows 10 + Visual Studio 2019 + Python 2/3 + CUDA 10.0 + GeForce GTX 1060

Внимание! Сборка не подойдет для версии OpenCV 4.0.1 и/или CUDA ниже 10-й версии. CUDA 9 и ниже поддерживается OpenCV 3.

Что потребуется для установки

В моей сборке использовались следующие инструменты:

  1. CMake 3.15
  2. MS Visual Studio 2019 64-бит + средства CMake С++ для Windows
  3. Python 3.7.3 64-бит + NumPy 64-бит
  4. Python 2.7.16 64-бит + NumPy 64-бит
  5. CUDA 10.0
  6. CuDNN 7.6.2
  7. OpenCV 4.1.1 и OpenCV-contrib-4.1.1

Установка

Так как установка производится через консольные команды, то следует внимательно и аккуратно выполнять все шаги. Также, при необходимости, меняйте установочные пути на свои.
Для начала необходимо установить требуемое ПО, причем Visual Studio должна быть установлена до CUDA:

  • CMake (версия >= 3.9.1)
  • MS Visual Studio
  • Python 3.7 (дистрибутив Anaconda3)
  • CUDA 10.0
  • CuDNN 7.6.2

После установки всех компонент убедитесь, что пути для CMake, Visual Studio, Python, CUDA, CuDNN прописаны в переменных PATH, PYTHONPATH, CUDA_PATH и cudnn соответственно.

Далее загружаем архивы исходников opencv-4.1.1 и opencv-contrib-4.1.1 в желаемое место (в моем случае это C:\OpenCV\).

git clone https://github.com/opencv/opencv.git -b "4.1.1"
git clone https://github.com/opencv/opencv_contrib.git -b "4.1.1"

Создаем папку build/ внутри opencv-4.1.1.

Далее сгенерируем файлы сборки с помощью cmake. Мы будем использовать консольный вариант cmake, так как cmake-gui путает типы некоторых переменных (например, OPENCV_PYTHON3_VERSION) и, как следствие, неправильно генерирует файлы.

Открываем консоль по пути C:\OpenCV\ и прописываем переменные.

set "opencvSource=opencv-4.1.1"
set "opencvExtraModules=opencv_contrib-4.1.1/modules"
set "opencvBuild=%opencvSource%\build"
set "compiler=Visual Studio 16 2019"
set "buildType=Release"

Примечание. Для Visual Studio 2017 генератор пишется как «Visual Studio 15 2017 Win64» и без флага -A.

Также можно явно указать питоновские библиотеки для python 2 и python 3 на случай, если сборщик не сможет найти их автоматически.

set "python2_executable=C:/Python27/python.exe"
set "python2_include_dir=C:/Python27/include"
set "python2_library=C:/Python27/libs/python27.lib"
set "python2_numpy_include_dirs=C:/Python27/Lib/site-packages/numpy/core/include"
set "python2_packages_path=C:/Python27/Lib/site-packages"

set "python3_executable=C:/Users/root/Anaconda3/python.exe"
set "python3_include_dir=C:/Users/root/Anaconda3/include"
set "python3_library=C:/Users/root/Anaconda3/libs/python37.lib"
set "python3_numpy_include_dirs=C:/Users/root/Anaconda3/lib/site-packages/numpy/core/include"
set "python3_packages_path=C:/Users/root/Anaconda3/Lib/site-packages"

Примечание. Обратите внимание на то, что библиотека NumPy должна быть той же разрядности, что и OpenCV. Проверить это легко:

import numpy.distutils.system_info as sysinfo
print(sysinfo.platform_bits)

Выполняем генерацию файлов сборки с помощью длинной команды ниже. При неудачной генерации или наличии ошибок после выполнения команды, повторную генерацию следует производить вычистив все файлы в build/ и .cache/.

cmake ^
-B"%opencvBuild%/" ^
-H"%opencvSource%/" ^
-G"%compiler%" ^
-Ax64 ^
-DCMAKE_BUILD_TYPE=%buildType% ^
-DBUILD_opencv_world=ON ^
-DINSTALL_TESTS=OFF ^
-DINSTALL_C_EXAMPLES=OFF ^
-DBUILD_EXAMPLES=OFF ^
-DOPENCV_EXTRA_MODULES_PATH="%opencvExtraModules%/" ^
-DBUILD_PROTOBUF=ON ^
-DBUILD_opencv_python_bindings_generator=ON ^
-DWITH_CUDA=ON ^
-DCUDA_FAST_MATH=ON ^
-DWITH_CUBLAS=ON ^
-DCUDA_ARCH_PTX=7.5 ^
-DBUILD_opencv_python2=ON ^
-DPYTHON2_EXECUTABLE="%python2_executable%" ^
-DOPENCV_PYTHON2_VERSION=2.7.16 ^
-DPYTHON2_INCLUDE_DIR="%python2_include_dir%" ^
-DPYTHON2_LIBRARY="%python2_library%" ^
-DPYTHON2_NUMPY_INCLUDE_DIRS="%python2_numpy_include_dirs%" ^
-DPYTHON2_PACKAGES_PATH="%python2_packages_path%" ^
-DBUILD_opencv_python3=ON ^
-DPYTHON3_EXECUTABLE="%python3_executable%" ^
-DOPENCV_PYTHON3_VERSION=3.7.3 ^
-DPYTHON3_INCLUDE_DIR="%python3_include_dir%" ^
-DPYTHON3_LIBRARY="%python3_library%" ^
-DPYTHON3_NUMPY_INCLUDE_DIRS="%python3_numpy_include_dirs%" ^
-DPYTHON3_PACKAGES_PATH="%python3_packages_path%"

Значение некоторых флагов

  • BUILD_opencv_world – необязательный модуль, содержащий копии всех выбранных в ходе установки библиотек. Удобен при разработке на C++, так как вместо подключения кучи зависимостей opencv можно подключить одну зависимость opencv_world411.lib в проект
  • INSTALL_EXAMPLES/INSTALL_TESTS – установка примеров/тестов кода opencv
  • CUDA_FAST_MATH, WITH_CUBLAS – дополнительные модули для CUDA, призванные ускорить вычисления
  • CUDA_ARCH_PTX – версия PTX инструкций для улучшения производительности вычислений
  • OPENCV_EXTRA_MODULES_PATH – путь до дополнительных модулей из opencv-contrib (обязательно для CUDA)
  • BUILD_PROTOBUF – для работы некоторых модулей opencv необходим Protobuf (сборщик opencv в любом случае поставит BUILD_PROTOBUF=ON)

Спустя примерно 10 минут в консоле должна появиться информация о сборке и завершающие строки «Configuring done» и «Generating done». Проверяем всю информацию, особенно разделы NVIDIA CUDA, Python 2, Python 3.

Далее собираем решение. На сборку может уйти несколько часов в зависимости от вашего процессора и версии Visual Studio.

cmake --build %opencvBuild% --target ALL_BUILD --config Release

Устанавливаем решение.

cmake --build %opencvBuild% --target INSTALL --config Release

После успешной установки создаем системную переменную OPENCV_DIR со значением C:\OpenCV\opencv-4.1.1\build\install\x64\vc15\bin и также добавляем ее в PATH.

Тест

Проверим работоспособность OpenCV с модулем CUDA на простом примере умножения матриц.

Подключение OpenCV в проект Visual Studio

  1. Установить тип сборки Release/x64 (для Debug следует собрать OpenCV с флагом Debug)
  2. Project Properties → C/C++ → General → Добавить строку «C:\OpenCV\opencv-4.1.1\build\install\include» в Additional Include Directories
  3. Project Properties → Linker → General → Добавить строку « C:\OpenCV\opencv-4.1.1\build\install\x64\vc16\lib» в Additional Library Directories
  4. Project Properties → Linker → General → Добавить «;opencv_world411.lib» («;opencv_world411d.lib» для Debug) в конец Additional Dependencies

Пример на Python 3

import numpy as np
import cv2 as cv
import time

rand = np.random.random((1024, 1024)).astype(np.float32)
h_array1 = np.stack([rand, rand],axis=2)
h_array2 = h_array1
d_array1 = cv.cuda_GpuMat()
d_array2 = cv.cuda_GpuMat()
d_array1.upload(h_array1)
d_array2.upload(h_array2)

start = time.time()
cv.cuda.gemm(d_array1, d_array2, 1, None, 0, None, 1)
end = time.time()
print("Time elapsed:", end - start, "sec")

Вывод в консоли

Time elapsed: 0.3130002021789551

Пример на C++

#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/cudaarithm.hpp>

using namespace std;
using namespace cv;
using namespace cv::cuda;

int main() {

	Mat h_array1 = Mat::ones(1024, 1024, CV_32FC2);
	Mat h_array2 = Mat::ones(1024, 1024, CV_32FC2);
	Mat h_array3 = Mat::zeros(1024, 1024, CV_32FC2);
	Mat h_result;
	GpuMat d_array1, d_array2, d_array3, d_result;

	d_array1.upload(h_array1);
	d_array2.upload(h_array2);

	const clock_t begin_time = clock();
	cuda::gemm(d_array1, d_array2, 1.0, d_array3, 0.0, d_result);
	cout << "Time elapsed: " << (float(clock() - begin_time) / CLOCKS_PER_SEC) << " sec" << endl;

	d_result.download(h_result);

	return 0;
}

Вывод в консоли

Time elapsed: 0.354

Удаление

Чтобы удалить OpenCV, нужно выполнить команду.

cmake --build %opencvBuild% --target uninstall --config Release

и удалить системную переменную OPENCV_DIR и убрать путь до OpenCV из PATH.

Заключение

В статье мы рассмотрели установку OpenCV 4 для ОС Windows 10. Данный алгоритм тестировался на Windows 8.1 и Windows 10, но, в теории, может собираться и на Windows 7. За дополнительной информацией можно обратиться к списку источников ниже.

P.S. Напоследок сведем все установочные команды в один .bat файл для тех, кто хочет автоматизировать установку.

install_opencv411.bat

cd C:\OpenCV

git clone https://github.com/opencv/opencv_contrib.git -b "4.1.1"
git clone https://github.com/opencv/opencv.git -b "4.1.1"

ren opencv opencv-4.1.1
ren opencv_contrib-4.1.1

set "opencvSource=opencv-4.1.1"
set "opencvExtraModules=opencv_contrib-4.1.1/modules"
set "opencvBuild=%opencvSource%\build"
set "compiler=Visual Studio 16 2019"
set "buildType=Release"

set "python2_executable=C:/Python27/python.exe"
set "python2_include_dir=C:/Python27/include"
set "python2_library=C:/Python27/libs/python27.lib"
set "python2_numpy_include_dirs=C:/Python27/Lib/site-packages/numpy/core/include"
set "python2_packages_path=C:/Python27/Lib/site-packages"

set "python3_executable=C:/Users/root/Anaconda3/python.exe"
set "python3_include_dir=C:/Users/root/Anaconda3/include"
set "python3_library=C:/Users/root/Anaconda3/libs/python37.lib"
set "python3_numpy_include_dirs=C:/Users/root/Anaconda3/lib/site-packages/numpy/core/include"
set "python3_packages_path=C:/Users/root/Anaconda3/Lib/site-packages"

cmake ^
-B"%opencvBuild%/" ^
-H"%opencvSource%/" ^
-G"%compiler%" ^
-Ax64 ^
-DCMAKE_BUILD_TYPE=%buildType% ^
-DBUILD_opencv_world=ON ^
-DINSTALL_TESTS=OFF ^
-DINSTALL_C_EXAMPLES=OFF ^
-DBUILD_EXAMPLES=OFF ^
-DOPENCV_EXTRA_MODULES_PATH="%opencvExtraModules%/" ^
-DBUILD_PROTOBUF=ON ^
-DBUILD_opencv_python_bindings_generator=ON ^
-DWITH_CUDA=ON ^
-DCUDA_FAST_MATH=ON ^
-DWITH_CUBLAS=ON ^
-DCUDA_ARCH_PTX=7.5 ^
-DBUILD_opencv_python2=ON ^
-DPYTHON2_EXECUTABLE="%python2_executable%" ^
-DOPENCV_PYTHON2_VERSION=2.7.16 ^
-DPYTHON2_INCLUDE_DIR="%python2_include_dir%" ^
-DPYTHON2_LIBRARY="%python2_library%" ^
-DPYTHON2_NUMPY_INCLUDE_DIRS="%python2_numpy_include_dirs%" ^
-DPYTHON2_PACKAGES_PATH="%python2_packages_path%" ^
-DBUILD_opencv_python3=ON ^
-DPYTHON3_EXECUTABLE="%python3_executable%" ^
-DOPENCV_PYTHON3_VERSION=3.7.3 ^
-DPYTHON3_INCLUDE_DIR="%python3_include_dir%" ^
-DPYTHON3_LIBRARY="%python3_library%" ^
-DPYTHON3_NUMPY_INCLUDE_DIRS="%python3_numpy_include_dirs%" ^
-DPYTHON3_PACKAGES_PATH="%python3_packages_path%"

cmake --build %opencvBuild% --target ALL_BUILD --config Release
cmake --build %opencvBuild% --target INSTALL --config Release

Список источников

  1. docs.opencv.org/4.1.1/d3/d52/tutorial_windows_install.html
  2. www.learnopencv.com/install-opencv-4-on-windows
  3. jamesbowley.co.uk/build-opencv-4-0-0-with-cuda-10-0-and-intel-mkl-tbb-in-windows
  4. lightbuzz.com/opencv-cuda
  5. Глава «Building libraries from Source» книги Hands-on GPU-Accelerated Computer Vision with OpenCV and CUDA



  • Star

    (19)


    You must be signed in to star a gist



  • Fork

    (7)


    You must be signed in to fork a gist

  • Clone this repository at &lt;script src=&quot;https://gist.github.com/demid5111/6faa590e4fc5813550dd95cc1c538893.js&quot;&gt;&lt;/script&gt;

  • Save demid5111/6faa590e4fc5813550dd95cc1c538893 to your computer and use it in GitHub Desktop.

Clone this repository at &lt;script src=&quot;https://gist.github.com/demid5111/6faa590e4fc5813550dd95cc1c538893.js&quot;&gt;&lt;/script&gt;

Save demid5111/6faa590e4fc5813550dd95cc1c538893 to your computer and use it in GitHub Desktop.

Instructions for installing opencv on Windows 10

Install OpenCV 4.5 on Windows 10

Pre-configured OpenCV for Python from PyPi

  1. open the terminal (Ctrl+R + cmd)
  2. check Python3 installation: py --version
  3. go to official website to learn details: https://pypi.org/project/opencv-python/
  4. choose the most complete package and run: py -m pip install opencv-contrib-python
  5. check installation by entering the Python REPL: py
  6. import tha library: import cv2

Pre-configured OpenCV for Python and C++ from GitHub releases

  1. Download opencv-4.5.1-vc14_vc15.exe from latest release:
    https://github.com/opencv/opencv/releases/tag/4.5.1
  2. unpack to C:\opencv
  3. edit environment variables. Win search «Environment variables»
  4. append to Path the path to opencv: C:\opencv\bin
  5. restart computer
  6. open cmd
  7. echo %Path% output should contain new path

Build OpenCV for Python and C++ from sources

  1. Install cmake. To check:
    cmake --version
  2. Download Source code (zip) from latest release:
    https://github.com/opencv/opencv/releases/tag/4.5.1
  3. Download Source code (zip) from latest release of opencv-contrib sources:
    https://github.com/opencv/opencv_contrib/releases/tag/4.5.1
  4. Unzip both archives
    Run cmake-gui
  5. choose the directory with opencv sources
  6. specify the directory for storing building binaries and Visual Studio project.
    it would better if you create a new one and specify it here
  7. press ‘Configure’
  8. use standard settings and proceed with Finish button
  9. once project is prepared, review all the flags suggested
  10. check BUILD_WITH_DEBUG_INFO
  11. important to specify: OPENCV_EXTRA_MODULES_PATH. We need to specify path to
    contrib folder we extracted earlier
  12. change CMAKE_INSTALL_PREFIX
    to a directory you want opencv to install to. for example C:/opencv-custom
  13. when you are ready, press Generate.
  14. go to build directory
  15. double click on OpenCV.sln
  16. build BUILD_ALL by right click on the corresponding project in Release configuration
  17. Then build INSTALL by right click on the corresponding project to finally install in Release configuration
  18. edit environment variables. Win search «Environment variables»
  19. append to Path the path to opencv: C:\opencv-custom\bin
  20. restart computer
  21. open cmd
  22. echo %Path% output should contain new path

Configure Visual Studio project to work with opencv

Go to the Visual Studio and create the new empty C++ project.

  1. We will call it «HelloOpenCV».
  2. Set the target to Debug and x64. This is very important to configure it for x64.
  3. Paste the main.cpp code to the main.cpp

As we can see there is unknown include statement of the opencv package. We need to fix that.

  1. For that we need to configure a project so that compiler could know where to take headers
    and library from. Open the Project->HelloOpenCV Properties and go to VC++ Directories.

  2. Change the Include Directories to contain corresponding include folder in the opencv
    installation. Insert it to the beginning of the value: C:\opencv\opencv\build\include;

  3. Change the Library directories to include C:\opencv\opencv\build\x64\vc15\lib

  4. Change the Linker->Input->Additional dependencies to

    1. include opencv_world451d.lib if we are talking about pre-configured package installation
    2. include opencv_core451d.lib;opencv_highgui451d.lib;opencv_videoio451d.lib;opencv_imgcodecs451d.lib;
      if we are talking about building from sources. In future, this list might be bigger
      containing all the libraries and extensions that you use from opencv and opencv-contrib.
  5. Apply and close the window

    To name the few more available libraries that can be included with the following linker flags
    (for Windows remove -l and add 451d.lib to the end if the version of opencv is 4.5.1:

    -lopencv_gapi -lopencv_stitching -lopencv_alphamat \
    -lopencv_aruco -lopencv_bgsegm -lopencv_bioinspired \
    -lopencv_ccalib -lopencv_dnn_objdetect -lopencv_dnn_superres \
    -lopencv_dpm -lopencv_face -lopencv_freetype \
    -lopencv_fuzzy -lopencv_hfs -lopencv_img_hash \
    -lopencv_intensity_transform -lopencv_line_descriptor -lopencv_mcc \
    -lopencv_quality -lopencv_rapid -lopencv_reg \
    -lopencv_rgbd -lopencv_saliency -lopencv_sfm \
    -lopencv_stereo -lopencv_structured_light -lopencv_phase_unwrapping \
    -lopencv_superres -lopencv_optflow -lopencv_surface_matching \
    -lopencv_tracking -lopencv_highgui -lopencv_datasets \
    -lopencv_text -lopencv_plot -lopencv_videostab \
    -lopencv_videoio -lopencv_viz -lopencv_xfeatures2d \
    -lopencv_shape -lopencv_ml -lopencv_ximgproc \
    -lopencv_video -lopencv_dnn -lopencv_xobjdetect \
    -lopencv_objdetect -lopencv_calib3d -lopencv_imgcodecs \
    -lopencv_features2d -lopencv_flann -lopencv_xphoto \
    -lopencv_photo -lopencv_imgproc -lopencv_core
    


This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

#include «opencv2/opencv.hpp«
#include <opencv2/highgui/highgui.hpp>
#include «iostream«
int showImage() {
std::string path = «img/test.jpeg«;
cv::Mat img = cv::imread(path);
imshow(«Portrait«, img);
cv::waitKey(0);
return 0;
}
int showWebCameraContent() {
// open the first webcam plugged in the computer
cv::VideoCapture camera(0);
if (!camera.isOpened()) {
std::cerr << «ERROR: Could not open camera« << std::endl;
return 1;
}
// create a window to display the images from the webcam
cv::namedWindow(«Webcam«);
// this will contain the image from the webcam
cv::Mat frame;
// display the frame until you press a key
while (1) {
// capture the next frame from the webcam
camera >> frame;
// show the image on the window
cv::imshow(«Webcam«, frame);
// wait (10ms) for a key to be pressed
if (cv::waitKey(10) >= 0) {
break;
}
}
return 0;
}
int main(int, char**) {
showImage();
// showWebCameraContent();
}

For developers wishing to explore computer vision, OpenCV is the best place to start. Installing OpenCV however is notoriously tricky. In this article we’ll step through a full build-from-source installation on Windows 10, including setting up Python and C++ development environments.

Building from Source

When installing OpenCV on Windows, we have two options. We can install pre-built binaries or perform our own build from source. The easiest way to get up and running quickly is to install the pre-built binaries. There are however a number of reasons why you may want to build from source:

  1. You want to be able to debug OpenCV code and step into OpenCV functions. The pre-built Windows distribution contains binary libraries for release builds only therefore, if you want to debug, you need to build from source.
  2. You want more control over the installation, for example which libraries and wrappers are included and which platforms are targeted.
  3. You want to modify the OpenCV source code in your application.
  4. You want to contribute to OpenCV development.

Installing the pre-built binaries is a great way to get started quickly however you will probably want to customize the install eventually as you get more familiar with what OpenCV has to offer. This article assumes you want to build from source and explains the full process on Windows 10.

Preparation

The first step is to download the source code. At the time of writing, the latest version of OpenCV is 4.2.0. The 4.2.0 source can be downloaded from OpenCV’s GitHub page. To have access to the latest OpenCV functionality, you will also want to download the contrib modules.

To build the OpenCV source code, a compiler is required. The suggested compiler for Windows is that provided by MSVC (Microsoft Visual C++). MSVC can either be installed as part of Microsoft Visual Studio or, if you don’t want the full Visual Studio install, you can just install the Visual Studio Build Tools. At the time of writing, the latest version of MSVC is version 16, which ships with Visual Studio 2019.

Unless you’re already familiar with C++, OpenCV’s Python interface is the best place to start. Regarding Python versions, the suggested version to use with OpenCV at the time of writing is Python 3.7. The more recent Python 3.8 has encountered issues with OpenCV bindings. Regarding target platforms, the default Python install available on www.python.org is x86 (32-bit). If you want to run x64 (64-bit) Python with OpenCV, the complication is that Numpy (a computational library which Python’s OpenCV bindings depend on) is only officially available in 32-bit format for Windows. The options therefore are as follows:

  1. Go with 32-bit Python and the official 32-bit Numpy package. This is the easiest option for getting started. Once 32-bit Python is installed, running the following command at the command prompt installs Numpy at the system level: pip3 install numpy.
  2. Use a 64-bit distribution of Python which includes 64-bit versions of supporting packages such as Numpy. Anaconda is the most common way of doing this. Distributions such as Anaconda are convenient as they have lots of tools readily available. The downside is you have less control over what is installed on your system and potentially many tools which you don’t need.
  3. Build your own 64-bit version of Numpy. This is only suggested if you’re familiar with building Python packages from source and you absolutely want to run with 64-bit Python and don’t want to work with a 3rd party distribution such as Anaconda.

To facilitate building from source, OpenCV uses CMake. The CMake tool is a free and open source utility which simplifies the build process with a graphical interface. CMake can be obtained from the downloads section of the CMake website. Be sure to add CMake to your Path during the installation process to allow it to be called from the command prompt.

Building the Binaries

Now the preparation steps are complete, we can start the build process. Once the source files are downloaded and extracted, you should see two folders as per the image below.

Launch the CMake utility and set the path of the source location. A build folder needs to be designated which CMake will create automatically. Be careful to use forward slashes instead of backslashes, which reflects CMake’s Linux origins.

Click the ‘Configure’ button and accept the creation of the build directory. CMake will then prompt you to specify the generator. Attention needs to be paid here to x64 vs x86. Depending which architecture you’re targeting (discussed earlier in this article regarding Python), the appropriate selection needs to be made. Note that MSVC version 16 (Visual Studio 2019) defaults to x64 whilst MSVC 15 (Visual Studio 2017) defaults to x86. You may therefore need to override the default setting using the ‘Optional toolset to use’ field.

Upon clicking ‘Finish’, CMake will proceed to create the build configuration files in the designated build directory. Once the initial configuration step is complete, there are a number of build configuration changes to make in the red window of the CMake utility. The following changes are suggested:

  1. Set CMAKE_INSTALL_PREFIX to the folder in which you want the binaries to be installed e.g. C:/Program Files/OpenCV
  2. Check INSTALL_C_EXAMPLES and INSTALL_PYTHON_EXAMPLES
  3. To have access to the full OpenCV functionality, check OPENCV_ENABLE_NONFREE
  4. To include the contrib modules, set OPENCV_EXTRA_MODULES_PATH to the contrib modules source location e.g. C:\Users\[user]\Downloads\opencv_contrib-4.2.0\opencv_contrib-4.2.0\modules
  5. Set PYTHON3_PACKAGES_PATH to where you want the Python bindings installed – by default this will be C:/Users/[user]/AppData/Local/Programs/Python/Python37-32/Lib/site-packages

Once the above changes have been completed, click ‘Configure’ again to update the build configuration files then click ‘Generate’ to generate the build files.

Once the build files are generated, we can proceed with the build itself. Open a command prompt, navigate to the build directory which contains CMake’s output and run the following command: cmake.exe –build . –config Release –target INSTALL. The command prompt may need to be opened with administrator privileges, depending on where the binaries are being installed. This process will take approximately 15 minutes, depending on your system. When complete, the binaries will be installed in the folder indicated by the CMAKE_INSTALL_PREFIX field during CMake configuration. If you want to add debug functionality, also run the following command in the build directory: cmake.exe –build . –config Debug –target INSTALL. To complete the build process, add the location of the binaries to your Path e.g. C:\Program Files\OpenCV\x64\vc16\bin (this will depend on the location indicated by the CMAKE_INSTALL_PREFIX field during CMake configuration.

Testing the Python bindings

If the PYTHON3_PACKAGES_PATH field in CMake was set to the system site packages folder (see CMake configuration section earlier in this article), OpenCV’s Python bindings should work without any further configuration. Launch the Python interpreter, paying attention to x64 vs x86 if you have multiple versions installed, and enter ‘import cv2’. If successful, you will receive no error messages and be able to check the version.

If you have errors when trying to import cv2, the most likely causes are either x64 vs x86 compatibility or the cv2 bindings not being on Python’s path. The x64 vs x86 compatibility issues are discussed earlier in this article: Python, Numpy and the compiler need to be aligned on the same architecture. Regarding Python’s path, the cv2 module may need to be added to the PYTHONPATH environment variable if the cv2 module was installed in a location other that the system site packages folder.

Setting up a C++ development environment

On Windows, the most common C++ development environment is Microsoft Visual Studio therefore we’ll focus on Visual Studio for this article. Once the compiled binaries are correctly installed, a development environment such as Visual Studio requires the paths to the include files and library files in order to work with an external library such as OpenCV.

The first step is to create an environment variable pointing to the install directory of the compiled binaries. This simplifies the addition of paths to Visual Studio and avoids having to modify the Visual Studio project from one machine to another. For example, on my machine, I created an environment variable called OPENCVDIR, pointing to C:\Program Files\OpenCV.

Within your Visual Studio C++ project, open the Project Properties dialogue and navigate to C/C++ > General. Under ‘Additional Include Directories’, add the environment variable created earlier, followed by the path to the include files.

The next step is to add the path to the libraries for linking. Again within the Project Properties dialogue, navigate to Linker > General and add the path to the library files under ‘Additional Library Directories’.

The final step is to add the specific library files to be linked under the Linker > Input section. To start with, it is suggested to add opencv_core420.lib, opencv_highgui420.lib, opencv_imgcodecs420.lib and opencv_imgproc420.lib. You can add more libraries later as you explore more of the OpenCV functionality.

Depending on whether you want to link statically or dynamically, a final step is to set the Runtime Library property within Project Properties > Configuration Properties > C/C++ > Code Generation. Your OpenCV C++ development environment is now setup and ready for building OpenCV applications.

Published by Jean on

A new version of OpenCV has been released so… Time to update!

(This is an updated version of the article I wrote months ago: Installing and using OpenCV 3.2 with Eclipse and MinGW on Windows 10. )

Getting started

– You will need:

  • OpenCV source code: version 3.4 or 3.3 (Link to Github repository (Latest release: 3.4.3));
  • (Optional) If you want the extra modules, you will need opencv_contrib (Version 3.4.3 can be found here)
  • Download MinGW-w64  and extract;
  • Download and install CMake.

Configuring OpenCV

  • Add MinGW to System Path
    – Edit your System Environment variables (you can search for Environment in Windows’ Start Menu) ;
    – Click on Path, and Edit;
    – Then, hit New, and add the address of your MinGW bin  folder.

Adding environment variables

  • Extract OpenCV to a folder, rename it opencv_src— Inside it, create a folder named Mingw_build

Now, let’s compile OpenCV

  • Open CMake-gui;
  • Set “Where is the source code:” to opencv_srcand “Where to build the binaries” to opencv_src/Mingw_build/
  • Click on Configure, choosing Eclipse CDT4 – MinGW MakeFilein the next window, then next;

Optional Step: OpenCV_Contrib Extra modules

  • If you want a simple and flawlessly working installation, just skip this step and go to the next, it’s not obligatory for you to have opencv_contrib.
    • For additional info, access its Modules Github Page.
  • After the “Configure” is finished, Set OPENCV_EXTRA_MODULES_PATH  to opencv_contrib/modules folder

Installing opencv_contrib

Building and Installing

  • After the “Configure”, on my PC I had to deselect the options ENABLE_PRECOMPILED_HEADERS and BUILD_opencv_python3  to correctly compile.
  • Hit “Generate”;
  • Now, open the CMD/PowerShell, and navigate to opencv_src/Mingw_build/
  • Inside opencv_src/Mingw_build  type mingw32make  and hit enter;- This step probably will take a while, wait until it’s finished.
  • Install using mingw32make install
  • Finally, add C:\opencv_src\Mingw_build\install\x64\mingw\binto your system path.
  • I have seen errors related also to the following parameters: WITH_PTHREADS_PF  , WITH_OPENCL  and ENABLE_CXX11  options. Try unchecking then if something occurs.

Configuring Eclipse

  • Open it and create a C++ program using the following OpenCV  example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

#include <opencv2/core/core.hpp>

#include <opencv2/highgui/highgui.hpp>

#include <iostream>

using namespace cv;

using namespace std;

int main( int argc, char** argv )

{

    if( argc != 2)

    {

     cout <<» Usage: thisprogramname.exe ImageToLoadAndDisplay» << endl;

     return 1;

    }

    Mat image;

    image = imread(argv[1], CV_LOAD_IMAGE_COLOR);   // Read the file

    if(! image.data )                              // Check for invalid input

    {

        cout <<  «Could not open or find the image» << std::endl ;

        return 1;

    }

    namedWindow( «Display window», WINDOW_AUTOSIZE );// Create a window for display.

    imshow( «Display window», image );                   // Show our image inside it.

    waitKey(0);                                          // Wait for a keystroke in the window

    return 0;

}

  • Go to
    Project > Properties > C/C++ Build > Settings > GCC C++ Compiler > Includes
    and add the source OpenCV folder

    C:\opencv_src\Mingw_build\install\include

Project data-lazy-src=

  • Go to
    Project > Properties > C/C++ Build > Settings > MinGW C++ Linker > Libraries
    , and add this to the Libraries (-l), separately as shown in the image
  • For OpenCV 3.4:

opencv_calib3d340 opencv_core340 opencv_features2d340 opencv_flann340 opencv_highgui340 opencv_imgcodecs340 opencv_imgproc340 opencv_ml340 opencv_objdetect340 opencv_photo340 opencv_shape340

  • For OpenCV 3.3:

opencv_calib3d330 opencv_core330 opencv_features2d330 opencv_flann330 opencv_highgui330 opencv_imgcodecs330 opencv_imgproc330 opencv_ml330 opencv_objdetect330 opencv_photo330 opencv_shape330

  • If you are using a different OpenCV version, change the number at end of each lib to match your version

  • You can  add additional libraries from lib folder if you need, just follow the presented format;
  • Add
    C:\opencv_src\Mingw_build\install\x64\mingw\lib
    to Library search path (-L);
  • Build the project. There are a lot of o ways of running it, e.g.:
    • Open the Powershell or CMD, go to the executable folder and type:
      yourprogramname.exe image.jpg
    • Or put the path of the image you want to show in the code, changing the following line:
      • image = imread(argv[1], CV_LOAD_IMAGE_COLOR);
        to
      • image = imread(«C://YOURIMAGEPATH.jpg», CV_LOAD_IMAGE_COLOR);
  • Updates

04/11/17 – Changed the order of some steps;
22/11/17 – Added MinGW-w64 instead of the conventional MinGW;
11/01/18 – Added support to OpenCV 3.4
12/04/18 – Added a better explanation for running the test code
12/09/18 – Added version 3.4.3 links and error correction sentences
 

Have fun with your projects! 
If this post helped you, please consider buying me a coffee 🙂

In this blog post, we will be installing OpenCV on Windows for C++ and Python. The C++ installation is done with the help of custom setup exe files. Whereas Python installation is done with Anaconda.

Installing OpenCV from source takes up a lot of time. Depending on your hardware, and the installation configuration, it can take anywhere from 5 minutes up to 2 hours.

Moreover, the installation is not a cakewalk. Hence, we have come up with a solution for Windows users – OpenCV Windows installers. These installers will only work for installing OpenCV for C++. If you want to install OpenCV for Python, you’ll find the information later in the blog.

If you want to install OpenCV 4 on Windows from source, then check out this blog post.

Table of Contents

Install OpenCV on Windows for CPP

Step 1: Prerequisites

You need Visual Studio pre-installed on your system. You can download the latest version of Visual Studio from here. Otherwise, you can find older versions from here.

Step 2: Download the Installer

Once you have set up Visual Studio on your system, download the installer according to the Visual Studio version you have installed.

Step 3: Install OpenCV on Windows

Once you download the installer, double click it to run the installer. Before the installer starts, it’ll ask you permission to run the executable. Click on More info and then on Run anyway.

Microsoft Defender SmartScreen protecting against phishing or malware files

Click on «More Info» to get the option to run the Installer
Microsoft Defender SmartScreen asking explicit permission to Run the installer anyway

Click on «Run anyway» to run the Installer

The installer starts with a welcome screen. Click on Next to read the License.

OpenCV Installer Welcome Screen

Welcome Screen

If you accept the license, click on I accept the agreement and click on Next.

OpenCV Installer License Agreement

License Agreement

Next, it’ll ask you to choose the installation folder. You can install OpenCV anywhere on the system. The default location is C:.

OpenCV Installer Select Destination

Select Installation Location

Finally, the installer will ask you for confirmation to install OpenCV on the system. Click on Install to continue.

OpenCV Installer Confirm Install

Confirm Install
OpenCV Installer Install OpenCV on Windows

Install

After OpenCV is installed, you can exit the installer.

OpenCV Installer Finish Installation

Finish Installation

Step 4: Execute a sample code

Once the OpenCV installation is completed, you can start coding right away. We have provided with a sample code to test the installation. Below is the code snippet.

 You can download the code using this link.

#include <opencv2/opencv.hpp>
using namespace cv;

int main(void) {

	// Read image in GrayScale mode
	Mat image = imread("boy.jpg", 0);

	// Save grayscale image
	imwrite("boyGray.jpg", image);

	// To display the image
	imshow("Grayscale Image", image);
	waitKey(0);

	return 0;
}

Download Code
To easily follow along this tutorial, please download code by clicking on the button below. It’s FREE!

If you plan on executing C++ code using Cmake, then download and install from here (windows win64-x64 Installer), and follow instructions below. The third line specifies the Visual Studio version on your system.

mkdir build 
cd build
cmake -G "Visual Studio 16 2019" ..
cmake --build . --config Release
cd ..
.\build\Release\sampleCode.exe

The above code reads an input image as grayscale, writes it to the disk, and displays it. Following are input and output to the code.

boy

Input image
Boy with spectacles in grayscale

Output image

How are the installers different from Official OpenCV Installers for Windows

These are general-purpose installers, which can install and uninstall OpenCV in under 15 seconds. It’s a quick and clean approach to install OpenCV for your Windows system. You can test out the latest OpenCV version and see if it’s for you. Otherwise, you can install OpenCV without configuring and waiting for hours on end for it to install.

Although the installers are useful for new users, or users who want one-click install, or simply for the ones who struggle with the installation, but these are not the official installers. You can find the official OpenCV binaries from here. There are differences between the installers which we provide and the OpenCV official binaries

  1. Contrib modules: The official binaries do not contain opencv_contrib modules. The installer which we provide does.
  2. Additional setup: The official binaries require additional setup, i.e., editing the environment variables, and using the correct folder address. Our installers will not require additional setup.
  3. Size: Official binaries are larger in size. They take about 1.21GB. The installers which we provide take around 367MB.
  4. List of libraries: If you code in Visual Studio, we have provided you with the list of libraries, in Debug and Release mode, as a separate text file. It is available in the root directory of the installation.
  5. No availability for VS16: The official binaries are not available for VS16, only for VS14 and VS15. Our installers are created for VS14, VS15, and VS16.

Install OpenCV on Windows for Python

Step 1: Install Anaconda for Python 3

Anaconda Installers download page

Download the Anaconda Installer

While installing Anaconda make sure that you check both options:

  • Add Anaconda to my PATH environment variable
  • Register Anaconda as my default Python

Step 2: Create a Virtual Environment

We will use Virtual Environment to install Python libraries. It is generally a good practice in order to separate your project environment and global environment.

Open the command prompt or Power shell and execute the following command.

conda create --name virtualenv python=3.8

Step 3: Install OpenCV on Windows

Activate the environment we created just now (virtualenv) and install all the required libraries using the commands below.

conda activate virtualenv
pip install opencv-contrib-python

And that’s it. OpenCV has been installed on your system. To close the virtual environment, use conda deactivate.

Step 4: Test Installation

Next, we will check whether the installation was successful. From the command prompt execute the following commands.

# activate environment
conda activate virtualenv

# start python prompt
python

# import cv2 and print version
import cv2
print(cv2.__version__)

# If OpenCV is installed correctly, the above command should output OpenCV version.

# Exit and deactivate environment
exit()
conda deactivate

Summary

In this blog post, we installed OpenCV on Windows with the quickest and easiest method. For C++, we used a simple .exe installer and installed in under 30 seconds. For Python, we used Anaconda as the package manager and installed OpenCV in a virtual environment. We also executed sample programs for both, C++ and Python, to test the installation. This concludes the OpenCV installation.

Subscribe & Download Code

If you liked this article and would like to download code (C++ and Python) and example images used in this post, please click here. Alternately, sign up to receive a free Computer Vision Resource Guide. In our newsletter, we share OpenCV tutorials and examples written in C++/Python, and Computer Vision and Machine Learning algorithms and news.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Иконки в стиле ios для windows
  • Windows updates disable gpo
  • Прокси сервер не отвечает как исправить windows
  • Где находятся ненужные файлы windows 10
  • Canon lbp6030w драйвер windows 10