Configuring an c++ OpenCV project with Cmake
- Create a new directory for your project:
mkdir my_opencv_project
cd my_opencv_project
- 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})
Create your C++ source file (e.g.,
main.cpp
) in the project directory.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;
}
- In your project directory, create a
build
directory to store the build artifacts:
mkdir build
cd build
- Run CMake to generate the build files:
cmake ..
- Build your project using the generated build files:
make
- Run your OpenCV application:
./my_opencv_app