Configuring an c++ OpenCV project with Cmake

  1. Create a new directory for your project:
mkdir my_opencv_project
cd my_opencv_project
  1. Create a CMakeLists.txt file in the project root:
cmake_minimum_required(VERSION 3.12)
project(my_opencv_project)

set(CMAKE_CXX_STANDARD 14)

find_package(OpenCV REQUIRED)

include_directories(${OpenCV_INCLUDE_DIRS})

add_executable(my_opencv_app main.cpp)

target_link_libraries(my_opencv_app ${OpenCV_LIBS})
  1. Create your C++ source file (e.g., main.cpp) in the project directory.

  2. Open main.cpp and write your OpenCV code.

#include <opencv2/opencv.hpp>

int main() {
    cv::Mat image = cv::imread("path/to/your/image.jpg", cv::IMREAD_COLOR);

    if (image.empty()) {
        std::cerr << "Error: Unable to read the image file." << std::endl;
        return -1;
    }

    // Your OpenCV code here

    cv::imshow("My OpenCV App", image);
    cv::waitKey(0);

    return 0;
}
  1. In your project directory, create a build directory to store the build artifacts:
mkdir build
cd build
  1. Run CMake to generate the build files:
cmake ..
  1. Build your project using the generated build files:
make
  1. Run your OpenCV application:
./my_opencv_app