1. 创建项目文件
- 创建cpp文件及CMakeLists.txt文件
- helloOpenCV.cpp
#include <opencv2/opencv.hpp>
int main() {
// 创建图像,初始化为黑色
cv::Mat image = cv::Mat::zeros(200, 300, CV_8UC3);
// 设置为纯绿色 (BGR格式:0, 255, 0)
image.setTo(cv::Scalar(0, 255, 0));
// 显示图像
cv::imshow("Green Image", image);
// 等待按键
cv::waitKey(0);
// 销毁所有窗口
cv::destroyAllWindows();
return 0;
}
- CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(helloOpenCV)
set(CMAKE_BUILD_TYPE "Debug")
find_package(OpenCV REQUIRED)
add_executable(helloOpenCV helloOpenCV.cpp)
target_link_libraries(helloOpenCV ${OpenCV_LIBS})
若编译过程提示缺少opencv库则执行 sudo apt install libopencv-dev
2. 生成可执行文件
# 在项目根目录下创建build文件夹
mkdir build
cd build
# 生成构建文件makefile
cmake ..
# 基于makefile构建项目生成可执行文件 helloOpencv
make
# 调用可执行程序 弹出图像
./helloOpenCV
3. vscode 调试环境配置
vscode调试环境主要包括三个文件的配置
- c_cpp_properties.json负责指定编译器及头文件路径
- tasks.json负责编译生成可执行文件
- launch.json负责可执行文件的调试
c_cpp_properties.json
快捷键 ctrl+shift+P 后选择 c/c++ : edit configurations(JSON)生成c_cpp_properties.json
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [],
"compilerPath": "/usr/bin/clang",
"cStandard": "c17",
"cppStandard": "c++14",
"intelliSenseMode": "linux-clang-x64"
}
],
"version": 4
}
其中较重要的字段包括:
- includePath:头文件搜索路径
- compilerPath:指定C/C++编译器的路径
- cppStandard:C++标准
- intelliSenseMode:智能补全模式
tasks.json
点击Terminal-Configure Default Build Task 在上述CMake: ***中任意选择一项生成tasks.json即可
- 方式1,通过自定义子task的顺序完成构建过程
{
"version": "2.0.0",
"tasks": [
{
"label": "cmake",
"type": "shell",
"command": "cmake",
"args": [
"../"
],
"options": {
"cwd": "${workspaceFolder}/build"
},
},
{
"label": "make",
"type": "shell",
"command": "make",
"args": [],
"options": {
"cwd": "${workspaceFolder}/build"
},
},
{
"label": "cmake task",
"dependsOn":["cmake", "make"],
"dependsOrder": "sequence"
},
],
}
- 方式2,通过调用shell脚本的形式完成构建过程(我更倾向的一种方式,定义更简单)
{
"version": "2.0.0",
"tasks": [
{
"label": "cmake task",
"type": "shell",
"command": "bash",
"args": ["${workspaceFolder}/build.sh"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
]
}
其中build.sh内容为
cd build
cmake ..
make
launch.json
点击Add configuration
将program改为要拉起的可执行程序,将prelaunchask设置为tasks.json中的label
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/helloOpenCV",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"preLaunchTask": "cmake task"
}
]
}
其中较重要的字段包括
- name:自定义命名运行与调式的名称,将在左侧运行和调试的菜单中显示名称
- type:调试器类型,C/C++的调试类型为cppdbg
- program:可执行文件路径
- environment:添加到程序的环境变量
- preLaunchTask:运行和调式前要启动的tasks任务,也即要启动的编译任务,任务名要和tasks.json里面的"label"值对应一致