đź’»

Setting Up and Running OpenCV C++ Programs with VS Code and CMake

Jul 14, 2024

Setting Up and Running OpenCV C++ Programs with VS Code and CMake

Introduction

  • Tutorial covers:
    • Installing CMake
    • Installing OpenCV
    • Setting up environment variables
    • Overview of CMakeLists.txt
    • Simple OpenCV program in C++
    • Configure step
    • Build and debug
    • Build and release
    • Modify program and rebuild
  • Channel topics: OpenCV, computer vision, Python, C++, Git, ROS 2, SolidWorks, mechanical design
  • GitHub repository available for resources

Installing CMake

  • Go to CMake website
  • For Windows (64-bit): download and run the Windows x64 installer

Installing OpenCV

  • Download OpenCV version 4.8.0
  • From the website, click on Windows and download the .exe file
  • Save the file in your desired path (e.g., opt path)
  • The downloaded OpenCV folder contains:
    • bin folder
    • lib folder

Setting Up Environment Variables

  • Create a variable OpenCV_DIR and set its value to the location of the OpenCV build folder
  • Add the following to the system Path environment variables:
    • CMake/bin
    • OpenCV/bin
    • OpenCV/lib
  • Instructions for accessing environment variables in Windows:
    • Press Windows key, type “system environment”, go to Environment Variables
    • Declare the variable and its value
    • Add paths to the system Path

CMakeLists.txt Overview

  • Example CMakeLists.txt file:
    • Specify minimum CMake version: cmake_minimum_required
    • Name the project: project(OpenCVExample)
    • Find OpenCV package: find_package(OpenCV REQUIRED)
    • Include necessary directories: include_directories
    • Add executable: add_executable
    • Link OpenCV libraries: target_link_libraries

Simple OpenCV C++ Program

  • Example code structure:
    • Main function: int main()
    • Read image: cv::imread("path/to/image")
    • Display image: cv::imshow("Display Image", img)
    • Wait for key press: cv::waitKey(0)

Configure Step

  • Create a build directory: mkdir build
  • Navigate to the build directory: cd build
  • Run CMake configure command: cmake ..
    • Specifying Visual Studio version, Windows SDK, compilers
    • Generates build files like .sln, CMakeCache.txt, and project files

Build and Debug

  • Build command for debug: cmake --build . --config Debug
  • Run the executable: build/Debug/OpenCVExample.exe
  • Example output: Displays the image read by the program

Build and Release

  • Build command for release: cmake --build . --config Release
  • Run the executable in release mode: build/Release/OpenCVExample.exe
  • Release mode is optimized for performance

Modify Program and Rebuild

  • Change the image path or code in main()
  • Rebuild the project: cmake --build .
  • Run the new executable: build/Debug/OpenCVExample.exe

Conclusion

  • Like and subscribe for more tutorials

[Music]