vscode+cmake+opencv调试

vscode+cmake+opencv调试

vscode与cmake的联合使用已经在使用CMAKE与VScode运行与调试C++讲过了,这样的话就加入opencv就行了,步骤也十分清晰

  1. 下载opencv源代码
  2. 用cmake进行编译安装
  3. 将编译后的opencv链接到项目中

1、下载opencv源代码

https://opencv.org/releases/,选择window,下载并安装到一个你喜欢的位置
vscode+cmake+opencv调试_第1张图片

2、使用cmake进行代码编译

想创建编译目录,在F:\e\opencv\opencv\build\x64中创建一个mybuild文件夹,在该文件夹中打开cmd

cmake -G "MinGW Makefiles" -D OPENCV_ENABLE_ALLOCATOR_STATS=OFF ..\..\..\sources\

此时会检查环境进行makefile的创建。
然后进行源码的编译

mingw32-make.exe -j 4

编译完成后进行opencv的安装

mingw32-make.exe install

安装完成后,mybuild目录下会出现一个install目录,此时就安装完成了,使用时只需要将

  • F:\e\opencv\opencv\build\x64\mybuild\install\include\opencv2中的文件放入include索引中
  • F:\e\opencv\opencv\build\x64\mybuild\lib中的文件放入到库索引中
  • 动态库 F:\e\opencv\opencv\build\x64\mybuild\binF:\e\opencv\opencv\build\x64\vc15\bin放入到环境变量中

上面的前两步都在CMakeLists.txt中完成

3、编写项目CMakeLists.txt

cmake_minimum_required(VERSION 3.0)
project(opencv_test)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(CMAKE_BUILD_TYPE debug)
include_directories(
    "F:/e/opencv/opencv/build/x64/mybuild/install/include/opencv2"
    "F:/e/opencv/opencv/build/x64/mybuild/install/include")
link_directories("F:/e/opencv/opencv/build/x64/mybuild/lib")

file(GLOB LIB "F:/e/opencv/opencv/build/x64/mybuild/lib/*")

add_executable(main main.cpp)
target_link_libraries(main ${LIB})

4、在.vscode中添加c_cpp_properties.json

让vscode能找到头文件,而不至于出现红色波浪线,按下ctrl+shift+p,按vscode的命令行中选择这个会自动生成c_cpp_properties.json,后面只需要改include就行了
vscode+cmake+opencv调试_第2张图片

{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**",
                "F:/e/opencv/opencv/build/x64/mybuild/install/include/opencv2", //将include位置告诉vscode
                "F:/e/opencv/opencv/build/x64/mybuild/install/include"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "windowsSdkVersion": "10.0.19041.0",
            "compilerPath": "D:/c/visual_studio/packages/VC/Tools/MSVC/14.29.30037/bin/Hostx64/x64/cl.exe",
            "cStandard": "c17",
            "cppStandard": "c++17",
            "intelliSenseMode": "windows-msvc-x64"
        }
    ],
    "version": 4
}

5、测试

main.cpp

#include 
#include 

using namespace cv;
using namespace std;

int main()
{
    cout<<"start";
    VideoCapture cap(0);
    Mat img;

    while (1)
    {
        cap >> img;
        if (img.empty())
            break;
        namedWindow("img", WINDOW_NORMAL);
        imshow("img", img);
        if (27 == waitKey(20))
            break;
    }

    return 0;
}

并且,在build文件夹中加入需要的dll(不然vscode无法调试),然后按下f5,就能愉快地运行了

你可能感兴趣的:(opencv,vscode,c++,cmake)