在Linux下使用VSCode開發OpenCV程序,並使用cmake編譯
創建項目
打開vscode,選擇File->Open Folder
VSCode配置
這里需要配置launch.json
, tasks.json
, c_cpp_properties.json
三個文件;
launch.json配置
點擊左側Debug, 選擇Add Configure,就生成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": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/${fileBasenameNoExtension}.main.out",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "build"
}
]
}
tasks.json配置
使用快捷鍵, Shirt+Ctrl+P
,輸入
>Tasks:Configure Default Build Task
選擇后,即可打開tasks.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": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/${fileBasenameNoExtension}.main.out",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "build"
}
]
}
c_cpp_properties.json配置
使用快捷鍵, Shirt+Ctrl+P
,輸入
>C/C++: Edit Configurations(JSON)
選擇后,即可打開c_cpp_properties.json
;
然后將下面內容拷貝進去,保存即可:
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"/usr/include",
"/usr/local/include/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"compilerPath": "/usr/bin/cpp",
"cStandard": "c11",
"cppStandard": "c++11",
"intelliSenseMode": "gcc-x64"
}
],
"version": 4
}
編寫CMakeFiles .txt文件
工作目錄下新建CMakeFiles.txt
文件,將下面內容拷貝進去:
cmake_minimum_required(VERSION 3.0)
project(cmake_usage)
set(cmake_minimum_required 11)
# for opencv
find_package(OpenCV 4.0.0 REQUIRED)
message("OpenCV version: ${OpenCV_VERSION}")
include_directories(${OpenCV_INCLUDE_DIRS})
link_directories(${OpenCV_LIB_DIR})
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})
編寫main.cpp
工作目錄下新建main.cpp
文件,將下面內容拷貝進去:
#include <iostream>
#include <stdlib.h>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
// Load the image
Mat img = imread("/home/chen/dataset/lena.jpg");
cout << img.rows << endl;
cout << img.cols << endl;
return 0;
}
編譯程序
在工作目錄下打開終端:
mkdir build
cd build
cmake ..
make
執行:
./cmake_usage
即可打印輸出信息;