This project demonstrates how to set up and use OpenCV with C++ in Visual Studio using CMake.
- Visual Studio 2019
- OpenCV 4.2.0
Install OpenCV via link https://opencv.org/releases/ and select download with Window option as shown in screenshot below.

Then, click on the OpenCV file we just downloaded (it should be named something like 'opencv-4.2.0-vc14_vc15.exe') and extract it to any directory. I prefer to install it in my C:/ drive, as shown in the figure below.
Now to be able to use OpenCV as a library, we have to add its path to system environment by searching "Edit the system environment variables" in our PC and add the path below to System Variable.
Note: the opencv path is depend on your setup and the path below is my setup and don't forget to click apply and okay to save your configuration.
C:/opencv/build/x64/vc15/bin
I downloaded Visual Studio 2019 from this link and chose the 'Free Community Edition' option and it works fine for me.
After downloading Visual Studio 20xx, open the downloaded file. During the installation, make sure to check the option shown in the figure below.
Installing Visual Studio might take some time, so sit back and relax!
If your Visual Studio installation is okay, then open the software and create a new project with CMake Project as shown. Then name your project and directory.
So your directory in your Visual Studio should be something like this:
project_root/
├── opencv_cpp_demo.cpp
├── opencv_cpp_demo.h
└── CMakeLists.txt
So to let the project reconigze your OpenCV library, we have to modify the CMakeList file as shown below.
From this:
# CMakeList.txt : CMake project for opencv_cpp_demo, include source and define
# project specific logic here.
#
cmake_minimum_required (VERSION 3.8)
project ("opencv_cpp_demo")
# Add source to this project's executable.
add_executable (opencv_cpp_demo "opencv_cpp_demo.cpp" "opencv_cpp_demo.h")
# TODO: Add tests and install targets if needed.To this:
cmake_minimum_required(VERSION 3.8)
project("opencv_cpp_demo")
# Tell CMake exactly where OpenCVConfig.cmake is
set(OpenCV_DIR "C:/opencv/build/x64/vc15/lib")
# Find OpenCV
find_package(OpenCV REQUIRED)
# Add your source files
add_executable(opencv_cpp_demo "opencv_cpp_demo.cpp" "opencv_cpp_demo.h")
# Link OpenCV
target_include_directories(opencv_cpp_demo PRIVATE ${OpenCV_INCLUDE_DIRS})
target_link_libraries(opencv_cpp_demo PRIVATE ${OpenCV_LIBS})
Then use the C++ code from this file opencv_cpp_demo to run the first demo opencv project. To run the project we have to click on:
And the result will be the same as below:





