第一步:安装OpenCV4和vscode。
可以参考这篇博客:Ubuntu20.4:安装OpenCV4,配置vscode+CMake作为基本开发环境_你和猫丶都要的博客-CSDN博客
网上相关文章很多,这里不再详述。
第二步:安装vscode C/C++插件。
打开vscode,点击Extensions搜索C/C++,点击安装即可。
第三步:配置OpenCV C++的编译环境。
在vscode内新建一个文件夹,新建一个test.cpp文件,编写一段包含opencv的调试代码。
按F5运行程序,会提示选择环境,依次选择C++(GDB/LLDB)->g++ - Build and debug active file,在左侧会生成一个.vscode文件夹,里面包含launch.json和tasks.json两个文件。
launch.json文件修改如下:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "g++ - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}", //程序文件路径
"args": [], //程序运行需传入的参数
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": true, //运行时是否显示控制台窗口
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: g++ build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
tasks.json文件修改如下:
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ build active file", /* 与launch.json文件里的preLaunchTask的内容保持一致 */
"command": "/usr/bin/g++",
"args": [
"-std=c++11",
"-g",
//"${file}", /* 编译单个文件 */
"${fileDirname}/*.cpp", /* 编译多个文件 */
"-o",
"${fileDirname}/${fileBasenameNoExtension}", /* 输出文件路径 */
/* 项目所需的头文件路径 */
"-I","${workspaceFolder}/",
"-I","/usr/local/include/",
"-I","/usr/local/include/opencv4/",
"-I","/usr/local/include/opencv4/opencv2",
/* 项目所需的库文件路径 */
"-L", "/usr/local/lib",
/* OpenCV的lib库 */
"/usr/local/lib/libopencv_*",
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
其中label的值必须与launch.json中preLaunchTask的值完全相同。
此时再按F5,程序已经可以正常编译运行。
第四步:配置OpenCV的开发环境。
Ctrl+Shift+P或者View->Command Palette打开命令面板,选择“C/C++:Edit Configurations(JSON)”,会在.vscode下生成一个c_cpp_properties.json文件,修改文件内容如下:
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"/usr/include",
"/usr/local/include/**"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "gnu11",
"cppStandard": "gnu++14",
"intelliSenseMode": "linux-gcc-x64"
}
],
"version": 4
}
主要是将include的头文件所在路径和函数库的路径设置给编译器。