Как подключить opencv к visual studio 2019
OpenCV is the Real-Time Computer Vision library which provides various real-time computer vision, video capturing, image processing, and machine learning functionalities. Using OpenCV with Visual Studio you can build robust applications for object detection, image transformation, video capturing, and analysis with fast C++ computations. Follow the given steps and instructions for your OpenCV C++ Windows Setup:
OpenCV Download and Installation:
Follow the below steps to download and install OpenCV on your local machine:
Step 2: Open the downloaded file. A self-extracting zip will open. Before proceeding with installation go and create a folder named OpenCV inside your C:\ drive. Run the installer and extract the zip file to the created folder C:\opencv
Step 3: Now that you have successfully installed OpenCV. The next step is to add binaries to the system path. Open a command prompt with admin privileges and write the command: setx -m OPENCV_DIR C:\opencv\build\x64\vc15 This will add OPENCV_dir as a system variable.
Step 4: Open Environment Variables Settings. Go to Path and add %OPENCV_DIR%\bin
OpenCV Setup is done here. The next step is to go ahead with the Visual Studio Project Configurations.
Visual Studio Project Configuration:
Step 1: Start a new Visual Studio project, and choose the C++ Console App template.
Step 2: After the Project has been created change the Debug to x64 platforms since we are using the x64 version at C:\opencv\build\x64\vc15
Step 3: Inside the Project, tab Open the Properties.
Step 4: Inside Configuration properties select VC++ Directories. The next step is to edit the included directories and library directories to add the OpenCV include directories and library directories. First Select Include Directories then Click on edit. A new window Pops up. Click on Add a new line which is a yellow colored button and enter the path for OpenCV include directories C:\opencv\build\include
Similarly for Library Directories Select Library directories and repeat the above steps. The only change will be the Library Directories path for OpenCV directories i.e. C:\opencv\build\x64\vc15\lib
After this is done go to Linker/Input inside the Project Properties and edit the Additional Dependencies to include the OpenCV DLL opencv_world450d.lib inside our linker.
Apply all the changes made and close the properties. Your OpenCV setup is done. Now you are ready to build amazing apps using OpenCV in C++. You have to repeat all these property changes every time you start a new OpenCV project with Visual Studio 2019.
Note: This is an update from a previous tutorial on how to add OpenCV 4.1.2 to Visual Studio 2019 in Windows. If you need to add OpenCV 4.1.2, please refer to the previous post.
The official documentation for OpenCV 4.2.0 still has vastly outdated contents on setting up OpenCV in Visual Studio (for C++). So, let’s take a quick dive into how to setup OpenCV 4.2.0 on Visual Studio 2019.
Environment
- Windows 10 (64-bit)
- Visual Studio 2019
To use OpenCV with Visual Studio 2019 (using C++), be sure to select Desktop development with C++ during Visual Studio install.
Run the downloaded .exe file to extract the archive.
For the sake of uniformity, this tutorial will assume that you’ve extracted the contents to c:\ . If you’d like to use a different path, it is completely fine. You simply need to adjust the paths in the later sections of this post.
The total extracted size will be about 1.2GB. Check your c:\ to ensure that you have the new opencv folder.
Add opencv’s bin directory to path. If you’ve extracted the downloaded .exe file into c:\ , the path to the bin directory should be c:\opencv\build\x64\vc15\bin .
In this step, we’re creating a new project in Visual Studio 2019. Note that the settings we set below are only applied to the new project. If you create a new project, you’ll need to repeat the steps below.
First, select Create a new project.
If you don’t see the “Console App” option in “Create a new project” window, it’s probably because you haven’t installed the required components for C++ development.
Click on Install more tools and features, and install Desktop development with C++ workload module.
Configure your project and continue. You can name the project however you’d like.
Before we go any further, I want to outline the steps we’re taking and why we are performing each step.
- Set platform target to x64 — Pre-built binaries are built for x64 Windows platforms.
- Add to Include Directories — Tell the compiler how the OpenCV library looks. This is done by providing a path to the header files ( build/include ).¹
- Add to Library Directories — Tell the linker where it can find the lib files for different modules.
- Add Additional Dependencies — List .lib files for different modules. Note that we’re only going to list a single all-in-one file named opencv_world .
Let’s move on. First, set platform target to x64. Also, make sure “Debug” is selected.
Now, go to Project → YourProjectName Properties in the menu.
Once new window opens up, select VC++ Directories page on the left and click on Include Directories row. Once you see the down arrow on the rightmost part of the row, click on the arrow, and select .
In Include Directories window, add c:\opencv\build\include .
Click OK. In the same tab, look for Library Directories. Again, click on the down arrow and select .
The VC++ Directories tab should look like below:
It’s time to list the module dependencies. As mentioned above, we are only going to add a single all-in-one module named opencv_world .
The Linker tab should look like below:
We now should be ready to write some OpenCV code and see it in action.
Copy and paste the code below and press F5 to run (or click on the Run button with the label “Local Windows Debugger”.
There we go. Have fun with OpenCV.
Please go over the previous steps carefully to see if you’ve made a typo or missed a step.
Also, if you’re getting an build error with the message “LNK 1104: Cannot open file ‘opencv_world4xxd.lib’, go to the lib directory at C:\opencv\build\x64\vc15\lib to check that the opencv_world420d.lib file exists. If it does, make sure the file name matches the additional dependency we’ve added to Linker Inputs.
If you run into any other issues, please feel free to let me know.
[1]: OpenCV Documentation. How to build applications with OpenCV inside the “Microsoft Visual Studio”
For some reason, the official documentation for OpenCV 4.1.2 has vastly outdated contents on setting up OpenCV for Visual Studio (for C++). So, let’s take a quick dive into how to setup OpenCV 4.1.2 on Visual Studio 2019.
Environment
- Windows 10 (64-bit)
- Visual Studio 2019
To use OpenCV with Visual Studio 2019 (using C++), be sure to select Desktop development with C++ during install
Run the downloaded .exe file to extract the archive.
For the sake of uniformity, this tutorial will assume that you’ve extracted the contents to c:\ .
Add opencv’s bin directory to path.
In this step, we’re creating a new project in Visual Studio 2019. Note that the settings we set below are only applied to the new project. If you create a new project, you’ll need to repeat the steps below.
Wait, what if I don’t see the “Console App” option in the previous step?
If you don’t see the “Console App” option in “Create a new project” window, it’s because you haven’t installed the required components for C++ development.
Click on Install more tools and features, and install Desktop development with C++ workload module.
Configure your project and continue. You can name the project however you’d like.
Before we go any further, I want to outline the steps we’re taking and why we are performing each step.
- Set platform target to x64 — Pre-built binaries are built for x64 Windows platforms.
- Add to Include Directories —Tell the compiler how the OpenCV library looks. This is done by providing a path to the header files ( build/include ).¹
- Add to Library Directories — Tell the linker where it can find the lib files for different modules.
- Add Additional Dependencies — List .lib files for different modules. Note that we’re only going to list a single all-in-one file named opencv_world .
Let’s move on. First, set platform target to x64.
Now, go to Project → YourProjectName properties in menu.
Once new window opens up, go to VC++ Directories on the left and click on Include Directories row. Once you see the down arrow on the rightmost part of the row, click on the arrow, and select .
In Include Directories window, add c:\opencv\build\include .
Click OK. In the same tab, look for Library Directories. Again, click on the down arrow and select .
The VC++ Directories tab should look like below:
It’s time to list the module dependencies. As mentioned above, we are only going to add a single all-in-one module named opencv_world .
We now should be ready to write some OpenCV code and see it in action.
Copy and paste the code below and press F5 to run (or click on the Run button with the label “Local Windows Debugger”.
There we go. Have fun with OpenCV.
If you run into any issues, please feel free to let me know.
[1]: OpenCV Documentation. How to build applications with OpenCV inside the “Microsoft Visual Studio”
At the time of writing this article, OpenCV 4.4.0 was the latest release.
2. Launch the executable, and extract it to C:\
2.1. Rename the target directory to reflect the release version
I use, OpenCV to keep it terse.
In my case, I renamed C:\opencv to C:\OpenCV_v440
3. Launch CMake and point it source.
…. For the build directory, create vc16 (Visual Studio 16 2019) in build\x64 as it doesn’t exist.
…. Click Configure.
…. specify generator from the drop down: Visual Studio 16 2019
…. set platform to x64
…. Click Generate
…. Click on Open Project
This should launch Visual Studio 2019.
…. Select Release
from build configuration drop down. Ensure target is x64.
…. Build Solution.
It might take a while based on your CPU. I’d give it 30 min and then check back.
4. Update System Path
…. Add the built binaries and dll’s path to system path
…. It should be in C:\OpenCV_v440\build\x64\vc16\bin\Release
5. Launch another instance of Visual Studio 2019
…. Select Create a new project
…. Select Console App
…. Provide your desired project name. Mine is called OpenCL-ML.
…. Click Create.
…. Open solution Properties by right clicking your project tree root (OpenCV-ML) in Solution explorer.
…. Ensure the configuration is set to Release and Platform to x64. By default, VS2019 uses default configuration and x86 target.
…. Include Headers
From the Configuration Properties tree, expand C/C++ > General and select Additional Include Directories. Click Edit.
…. Point it to OpenCV headers built from CMake/VS2019 earlier.
…. It should be in C:\OpenCV_v440\build\include
…. Setup Linker
From the Configuration Properties tree, expand Linker > General and select Additional Linker Directories. Click Edit.
…. point it to OpenCV libraries built from CMake/VS2019 earlier.
…. It should be in C:\OpenCV_v440\build\x64\vc16\Release
From the Configuration Properties tree, expand Linker > Input and select Additional Dependencies. Click Edit.
Point it to fetch all libraries.
6. Now the Fun Stuff !
Copy the following code into your project
…. Build the solution
…. Download the image below
…. Save it to C:\\Pictures in a new folder named assets.
…. Open Solution Properties, and From the Configuration Properties tree, select Debugging > Command Arguments.
…. Point it to the image path downloaded from last step.
…. Run the program
…. This show bring up an image window showing the image
В данной статье речь пойдет о сборке и установке 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
Что потребуется для установки
В моей сборке использовались следующие инструменты:
- CMake 3.15
- MS Visual Studio 2019 64-бит + средства CMake С++ для Windows
- Python 3.7.3 64-бит + NumPy 64-бит
- Python 2.7.16 64-бит + NumPy 64-бит
- CUDA 10.0
- CuDNN 7.6.2
- OpenCV 4.1.1 и OpenCV-contrib-4.1.1
Установка
Так как установка производится через консольные команды, то следует внимательно и аккуратно выполнять все шаги. Также, при необходимости, меняйте установочные пути на свои.
Для начала необходимо установить требуемое ПО, причем Visual Studio должна быть установлена до CUDA:
Далее загружаем архивы исходников opencv-4.1.1 и opencv-contrib-4.1.1 в желаемое место (в моем случае это C:\OpenCV\).
Создаем папку build/ внутри opencv-4.1.1.
Далее сгенерируем файлы сборки с помощью cmake. Мы будем использовать консольный вариант cmake, так как cmake-gui путает типы некоторых переменных (например, OPENCV_PYTHON3_VERSION) и, как следствие, неправильно генерирует файлы.
Открываем консоль по пути C:\OpenCV\ и прописываем переменные.
Примечание. Для Visual Studio 2017 генератор пишется как «Visual Studio 15 2017 Win64» и без флага -A.
Также можно явно указать питоновские библиотеки для python 2 и python 3 на случай, если сборщик не сможет найти их автоматически.
Примечание. Обратите внимание на то, что библиотека NumPy должна быть той же разрядности, что и OpenCV. Проверить это легко:
Выполняем генерацию файлов сборки с помощью длинной команды ниже. При неудачной генерации или наличии ошибок после выполнения команды, повторную генерацию следует производить вычистив все файлы в build/ и .cache/.
- 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.
После успешной установки создаем системную переменную OPENCV_DIR со значением C:\OpenCV\opencv-4.1.1\build\install\x64\vc15\bin и также добавляем ее в PATH.
Проверим работоспособность OpenCV с модулем CUDA на простом примере умножения матриц.
- Установить тип сборки Release/x64 (для Debug следует собрать OpenCV с флагом Debug)
- Project Properties → C/C++ → General → Добавить строку «C:\OpenCV\opencv-4.1.1\build\install\include» в Additional Include Directories
- Project Properties → Linker → General → Добавить строку « C:\OpenCV\opencv-4.1.1\build\install\x64\vc16\lib» в Additional Library Directories
- Project Properties → Linker → General → Добавить «;opencv_world411.lib» («;opencv_world411d.lib» для Debug) в конец Additional Dependencies
Пример на Python 3
Вывод в консоли
Пример на C++
Вывод в консоли
Удаление
Чтобы удалить OpenCV, нужно выполнить команду.
и удалить системную переменную OPENCV_DIR и убрать путь до OpenCV из PATH.
Заключение
В статье мы рассмотрели установку OpenCV 4 для ОС Windows 10. Данный алгоритм тестировался на Windows 8.1 и Windows 10, но, в теории, может собираться и на Windows 7. За дополнительной информацией можно обратиться к списку источников ниже.
OpenCV C++ Windows Setup using Visual Studio 2019
OpenCV is the Real-Time Computer Vision library which provides various real-time computer vision, video capturing, image processing, and machine learning functionalities. Using OpenCV with Visual Studio you can build robust applications for object detection, image transformation, video capturing, and analysis with fast C++ computations. Follow the given steps and instructions for your OpenCV C++ Windows Setup:
OpenCV Download and Installation:
Follow the below steps to download and install OpenCV on your local machine:
Step 2: Open the downloaded file. A self-extracting zip will open. Before proceeding with installation go and create a folder named OpenCV inside your C:\ drive. Run the installer and extract the zip file to the created folder C:\opencv
Step 3: Now that you have successfully installed OpenCV. The next step is to add binaries to the system path. Open a command prompt with admin privileges and write the command: setx -m OPENCV_DIR C:\opencv\build\x64\vc15 This will add OPENCV_dir as a system variable.
Step 4: Open Environment Variables Settings. Go to Path and add %OPENCV_DIR%\bin
OpenCV Setup is done here. The next step is to go ahead with the Visual Studio Project Configurations.
Visual Studio Project Configuration:
Step 1: Start a new Visual Studio project, and choose the C++ Console App template.
Step 2: After the Project has been created change the Debug to x64 platforms since we are using the x64 version at C:\opencv\build\x64\vc15
Step 3: Inside the Project, tab Open the Properties.
Step 4: Inside Configuration properties select VC++ Directories. The next step is to edit the included directories and library directories to add the OpenCV include directories and library directories. First Select Include Directories then Click on edit. A new window Pops up. Click on Add a new line which is a yellow colored button and enter the path for OpenCV include directories C:\opencv\build\include
Similarly for Library Directories Select Library directories and repeat the above steps. The only change will be the Library Directories path for OpenCV directories i.e. C:\opencv\build\x64\vc15\lib
After this is done go to Linker/Input inside the Project Properties and edit the Additional Dependencies to include the OpenCV DLL opencv_world450d.lib inside our linker.
Apply all the changes made and close the properties. Your OpenCV setup is done. Now you are ready to build amazing apps using OpenCV in C++. You have to repeat all these property changes every time you start a new OpenCV project with Visual Studio 2019.
Установка OpenCV 3 в Windows
Большинство мануалов в интернетах предлагают собрать opencv самостоятельно. Это процесс не быстрый да и требует некоторых умений.
Гораздо проще воспользоваться готовой сборкой библиотеки.
Обратите внимание, что так Вы не сможете использовать статическую библиотеку. В поставке для Windows таковые отсутствуют. Их можно только собрать самостоятельно.
Но какая нам разница. Мы будем пользоваться собранной DLL, которую не нужно собирать.
Как установить OpenCV в Windows
Теперь идем в Мой компьютер — Свойства — Дополнительные параметры системы — Переменные среды
Создаем переменную OPENCV_DIR:
Теперь добавляем opencv в системный путь. Редактируем переменную PATH:
Как создать проект Visual Studio с OpenCV
Создаем новый проект — Win32 Console Application.
Жмем Finish, можно конечно понастраивать, но мы этого делать не будем.
Идем в настройки проекта — Project — Properties.
Переключаем в верхней части окна Platforms в положение All Platforms.
Выбираем в левом столбце C/C++ — General.
Добавляем путь к заголовкам opencv — Additional Include Directories.
Переходим в настройки компановщика — Linker — General.
Здесь указываем путь к файлам lib opencv.
Добавляем DLL opencv как зависимость.
Переходим в Linker — Input и добавляем в поле Additional Dependencies:
или debug версию
Теперь в каталог с исходными файлами кладем любимую картинку.
Для теста используем такую программу.
Эта программа в качестве параметра использует параметр командной строки — имя файла изображения.
Укажем его. Переходим в Project Properties — Debugging.
Указываем имя файла в строке Command Arguments.
Радуемся. Мы собрали наше первое 64 битное Windows приложение OpenCV в Visual Studio.
Читайте также: