一次搞定!如何用VSCode编写OpenCV

首先,需要安装MinGW编译器,支持编译C++代码。

安装MinGW编译器

  1. 下载MinGW,下载链接为:
    https://nchc.dl.sourceforge.net/project/mingw-w64/Toolchains%20targetting%20Win64/Personal%20Builds/mingw-builds/8.1.0/threads-posix/sjlj/x86_64-8.1.0-release-posix-sjlj-rt_v6-rev0.7z

  2. 将MinGW解压缩在某个文件夹中。例如:C:\software\mingw64
    mingw路径

  3. 配置环境变量。

    3.1 右键桌面此电脑,选择属性。
    此电脑-属性
    3.2 选择高级系统设置。
    高级系统设置
    3.3 打开环境变量。
    环境变量
    3.4 设置path,添加一条路径,为刚刚mingw的下bin文件夹的路径。C:\software\mingw64\bin。
    path环境变量
    path变量

  4. 测试环境变量。win+r打开运行界面,输入cmd进入命令行,输入gcc -v,敲回车,查看gcc是否正常工作。
    gcc正常工作

配置Vscode环境,支持编译C++

不用怎么配置,新建一个.cpp文件,用vscode打开,右下角提示是否安装推荐的C++扩展,安装之后就可以编译cpp文件了。
安装完成后,发现新增了如下的VSCode扩展。
新增的C++扩展

下载opencv3

进入官网,https://opencv.org/releases/,下载opencv3,选择Windows进行下载。Opencv3 Windows
安装到指定目录下即可。
opencv3

下载Cmake

下载路径是:https://cmake.org/download/

cmake
将其解压到自定义目录下,我的路径为:C:\software\cmake\bin
cmake文件夹
点开cmake-gui.exe。
where is source code,选择C:\software\opencv3\opencv\sources
where is to build the binaries,是自己设置的文件夹,选择C:\software\opencv3\opencv\build\x64\mingw。
路径

点击左下角的Configure,选择MinGW Makefiles,Specify native compiler。
Configure
Compiler,选择Mingw文件夹bin下的gcc.exe和g++.exe。路径是C:\software\mingw64\bin。
gcc, g++
显示configure done。

一定注意这一步,如果不执行这一步,后面依赖的world等dll会缺失。

在执行完后,把关于python的都给取消勾选。勾选BUILD_opencv_world,WITH_OPENGL和BUILD_EXAMPLES,不勾选WITH_IPP、WITH_MSMF和ENABLE_PRECOMPILED_HEADERS(如果有的话),CPU_DISPATCH选空。

这里有一个巨大的坑等着我去踩,解决下面的问题耗费了我两天的时间。如果有后面的人发现自己的opencv C++程序无法正常读取.mp4等视频文件,显示mp4视频文件为零帧、VideoCapture 的isOpened显示为false,是因为在camke的时候没有成功安装ffmpeg。

也就是,执行完configure之后,显示


  Video I/O:
    DC1394:                      NO
    FFMPEG:                      NO
      avcodec:                   NO
      avformat:                  NO
      avutil:                    NO
      swscale:                   NO
      avresample:                NO
    GStreamer:                   NO
    DirectShow:                  YES

此时,按照下面的步骤进行。

  1. Ctrl+A,复制指示区的显示内容。
    描述区的文件
  2. 复制到一个笔记本里面,搜索其中的failed关键词,找到关于ffmpeg的下载失败内容。内容显示,opencv_ffmpeg.dll, opencv_ffmpeg_64.dll, ffmpeg_version.cmake三个文件下载失败,无法正常运行。
FFMPEG: Download: opencv_ffmpeg.dll
Try 1 failed

=======================================================================
  Couldn't download files from the Internet.
  Please check the Internet access on this host.
=======================================================================

CMake Warning at cmake/OpenCVDownload.cmake:202 (message):
  FFMPEG: Download failed: 6;"Couldn't resolve host name"

  For details please refer to the download log file:

  C:/software/opencv3/opencv/build/x64/mingw/CMakeDownloadLog.txt

Call Stack (most recent call first):
  3rdparty/ffmpeg/ffmpeg.cmake:20 (ocv_download)
  cmake/OpenCVFindLibsVideo.cmake:227 (download_win_ffmpeg)
  CMakeLists.txt:701 (include)


FFMPEG: Download: opencv_ffmpeg_64.dll
Try 1 failed

=======================================================================
  Couldn't download files from the Internet.
  Please check the Internet access on this host.
=======================================================================

CMake Warning at cmake/OpenCVDownload.cmake:202 (message):
  FFMPEG: Download failed: 6;"Couldn't resolve host name"

  For details please refer to the download log file:

  C:/software/opencv3/opencv/build/x64/mingw/CMakeDownloadLog.txt

Call Stack (most recent call first):
  3rdparty/ffmpeg/ffmpeg.cmake:20 (ocv_download)
  cmake/OpenCVFindLibsVideo.cmake:227 (download_win_ffmpeg)
  CMakeLists.txt:701 (include)


FFMPEG: Download: ffmpeg_version.cmake
Try 1 failed

=======================================================================
  Couldn't download files from the Internet.
  Please check the Internet access on this host.
=======================================================================

CMake Warning at cmake/OpenCVDownload.cmake:202 (message):
  FFMPEG: Download failed: 6;"Couldn't resolve host name"

  For details please refer to the download log file:

  C:/software/opencv3/opencv/build/x64/mingw/CMakeDownloadLog.txt

Call Stack (most recent call first):
  3rdparty/ffmpeg/ffmpeg.cmake:20 (ocv_download)
  cmake/OpenCVFindLibsVideo.cmake:227 (download_win_ffmpeg)
  CMakeLists.txt:701 (include)

  1. 按照上面的提示报错路径,打开C:/software/opencv3/opencv/build/x64/mingw/CMakeDownloadLog.txt,该文件包含了下载错误的提示信息。
#use_cache "C:/software/opencv3/opencv/sources/.cache"
#do_copy "opencv_ffmpeg.dll" "55c25bbc13e4a12d4339b70d3b76987f" "https://raw.githubusercontent.com/opencv/opencv_3rdparty/0bf6c0753d435d2c82c03c48db0c6e18ac79976c/ffmpeg/opencv_ffmpeg.dll" "C:/software/opencv3/opencv/build/x64/mingw/3rdparty/ffmpeg"
#missing "C:/software/opencv3/opencv/build/x64/mingw/3rdparty/ffmpeg/opencv_ffmpeg.dll"
#cmake_download "C:/software/opencv3/opencv/sources/.cache/ffmpeg/55c25bbc13e4a12d4339b70d3b76987f-opencv_ffmpeg.dll" "https://raw.githubusercontent.com/opencv/opencv_3rdparty/0bf6c0753d435d2c82c03c48db0c6e18ac79976c/ffmpeg/opencv_ffmpeg.dll"
#try 1
# timeout on name lookup is not supported
# getaddrinfo(3) failed for raw.githubusercontent.com:443
# Could not resolve host: raw.githubusercontent.com
# Closing connection 0
# 

#do_copy "opencv_ffmpeg_64.dll" "67caee9231c6843483b4de9815d6526e" "https://raw.githubusercontent.com/opencv/opencv_3rdparty/0bf6c0753d435d2c82c03c48db0c6e18ac79976c/ffmpeg/opencv_ffmpeg_64.dll" "C:/software/opencv3/opencv/build/x64/mingw/3rdparty/ffmpeg"
#missing "C:/software/opencv3/opencv/build/x64/mingw/3rdparty/ffmpeg/opencv_ffmpeg_64.dll"
#cmake_download "C:/software/opencv3/opencv/sources/.cache/ffmpeg/67caee9231c6843483b4de9815d6526e-opencv_ffmpeg_64.dll" "https://raw.githubusercontent.com/opencv/opencv_3rdparty/0bf6c0753d435d2c82c03c48db0c6e18ac79976c/ffmpeg/opencv_ffmpeg_64.dll"
#try 1
# timeout on name lookup is not supported
# getaddrinfo(3) failed for raw.githubusercontent.com:443
# Could not resolve host: raw.githubusercontent.com
# Closing connection 0
# 

#do_copy "ffmpeg_version.cmake" "3b90f67f4b429e77d3da36698cef700c" "https://raw.githubusercontent.com/opencv/opencv_3rdparty/0bf6c0753d435d2c82c03c48db0c6e18ac79976c/ffmpeg/ffmpeg_version.cmake" "C:/software/opencv3/opencv/build/x64/mingw/3rdparty/ffmpeg"
#missing "C:/software/opencv3/opencv/build/x64/mingw/3rdparty/ffmpeg/ffmpeg_version.cmake"
#cmake_download "C:/software/opencv3/opencv/sources/.cache/ffmpeg/3b90f67f4b429e77d3da36698cef700c-ffmpeg_version.cmake" "https://raw.githubusercontent.com/opencv/opencv_3rdparty/0bf6c0753d435d2c82c03c48db0c6e18ac79976c/ffmpeg/ffmpeg_version.cmake"
#try 1
# timeout on name lookup is not supported
# getaddrinfo(3) failed for raw.githubusercontent.com:443
# Could not resolve host: raw.githubusercontent.com
# Closing connection 0
# 


该文件内容很长,但是不要慌,最终的目的是手动下载三个没能下载成功的文件,将它们放到.cache文件夹中。

  1. 按照CMakeDownloadLog.txt该文件夹中的内容,我们打开C:/software/opencv3/opencv/sources/.cache文件夹,下面有ffmpeg文件夹,继续打开,发现里面放着三个下载失败的0KB文件。
    下载失败
  2. 按照CMakeDownloadLog.txt文件中的提示,我们要下载三个对应的文件,分别复制到该文件夹下,并且要求修改文件名和.cache/ffmpeg文件夹下的名称相同。
    .dll文件的下载链接,就是CMakeDownloadLog.txt文件中的对应链接。
"https://raw.githubusercontent.com/opencv/opencv_3rdparty/0bf6c0753d435d2c82c03c48db0c6e18ac79976c/ffmpeg/opencv_ffmpeg.dll" 

"https://raw.githubusercontent.com/opencv/opencv_3rdparty/0bf6c0753d435d2c82c03c48db0c6e18ac79976c/ffmpeg/opencv_ffmpeg_64.dll"

"https://raw.githubusercontent.com/opencv/opencv_3rdparty/0bf6c0753d435d2c82c03c48db0c6e18ac79976c/ffmpeg/ffmpeg_version.cmake" 

修改后的前缀名要保证是与自己的Log文件夹中对应的字符串,这串字符是.md5加密串,后续编译过程,编译器会检查该串与文件的.md5是否相同。

 "55c25bbc13e4a12d4339b70d3b76987f" 

"67caee9231c6843483b4de9815d6526e" 

"3b90f67f4b429e77d3da36698cef700c" 

特别注意的是,.cmake文件从浏览器打开之后,是一个类似文本文档被浏览器打开的内容。
.cmake文件
但是,不要将该段文字复制、粘贴到.cache文件夹下的.cmake文件中,因为该下载失败的文件的md5与目标md5是不同的,后续检查会报错。正确做法是Ctrl+S,保存该页面,文件名存为3b90f67f4b429e77d3da36698cef700c-ffmpeg_version.cmake。
在这里插入图片描述
6. 将上述三个文件,放到.cache文件夹中,如下。
ffmpeg文件

至此,就把ffmpeg的隐患解决了。

第二次点击Configure。

configure done
再点击Generate,最后Generate Done,就完成了。

  Video I/O:
    DC1394:                      NO
    FFMPEG:                      YES (prebuilt binaries)
      avcodec:                   YES (ver 57.107.100)
      avformat:                  YES (ver 57.83.100)
      avutil:                    YES (ver 55.78.100)
      swscale:                   YES (ver 4.8.100)
      avresample:                YES (ver 3.7.0)
    GStreamer:                   NO
    DirectShow:                  YES

make

cmd进入刚刚设置的文件夹C:\software\opencv3\opencv\build\x64\mingw,执行命令: minGW32-make -j 4。
mingw32-make -j 4
make成功
编译完成
继续执行minGW32-make install
执行成功
配置OpenCV的环境变量。
opencv环境变量

配置Vscode环境,支持OpenCV3

任意创建一个文件夹,放置自己的代码。
最后的文件结构如下:
文件结构
自己创建.vscode文件夹,自己创建c_cpp_properties.json、launch.json、tasks.json文件。自己创建Debugger文件夹。

c_cpp_properties.json

{
    "configurations": [
        {
            "name": "win",
            "includePath": [
                "${workspaceFolder}/**",
                "C:/software/opencv3/opencv/build/x64/mingw/include",
                "C:/software/opencv3/opencv/build/x64/mingw/install/include/opencv2",
                "C:/software/opencv3/opencv/build/x64/mingw/install/include"
            ],
            "defines": [],
            "compilerPath": "C:/software/mingw64/bin/g++.exe",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "${default}"
        }
    ],
    "version": 4
}

launch.json

{

    "version": "0.2.0",
    "configurations": [
        {
            "name": "opencv debuge",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}//Debugger//${fileBasenameNoExtension}.exe",
            //上面这个Debugger是我自己定义的,为了方便放置生成的exe文件
            "args": [],
            "stopAtEntry": false, //这里如果为 false,则说明调试直接运行。(反之则停止)
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,//是否调用外部cmd
            "MIMode": "gdb",
            "miDebuggerPath": "C:/software/mingw64/bin/gdb.exe",//自己进行设置
            "setupCommands": [
                {
                    "description": "为 gdb 启用整齐打印",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": false
                }
            ],
            "preLaunchTask": "opencv3.5.2"
        }
    ]
}

tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "opencv3.5.2",
            "command": "C:/software/mingw64/bin/g++.exe",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${workspaceFolder}//Debugger//${fileBasenameNoExtension}.exe",
                //上面这个Debugger是我自己定义的,为了方便放置生成的exe文件
                "C:/software/opencv3/opencv/build/x64/mingw/bin/libopencv_world3416.dll",
                "-I",
                "C:/software/opencv3/opencv/build/x64/mingw/install/include",
                "-I",
                "C:/software/opencv3/opencv/build/x64/mingw/install/include/opencv2",
            ],
            "options": {
                "cwd": "C:/software/mingw64/bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

在C:\software\opencv3\opencv\build\x64\mingw\bin下找到libopencv_world3416.dll,和opencv_ffmpeg3416_64.dll复制到Debugger文件夹下。注意这个后缀3416是OpenCV的版本号,与自己安装的版本有关系。

生成test.cpp文件,输入测试代码。

#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
using namespace cv;
int main()
{
    Mat img=imread("man.jpg");
    imshow("image",img);
    waitKey();
    return 0;
}

能正常运行,就表示图片可以正常运行了。

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace std;

int main(int argc, char** argv){
    cv::namedWindow("Example3", cv::WINDOW_AUTOSIZE);
    cv::VideoCapture cap;
    cap.open("test.mp4");
    cout<<cap.isOpened()<<endl;
    cv::Mat img; 
    cap >> img;
    std::cout << "image read: " << (img.empty()==true) << std::endl;
    cv::Mat frame;
    for(;;){
        cap >> frame;
        if(frame.empty()) break; // Ran out of film
        cv::imshow("Example3", frame);
        if(cv::waitKey(10) >= 0) break;
    }
    return 0;
}

视频可以正常读取,就表示视频也OK了!
wow!至此,一切成功!

你好!为了在VS Code中配置OpenCV,你需要完成以下步骤: 1. 首先,确保你已经安装了VS Code和C/C++扩展。你可以在VS Code的扩展面板中搜索并安装这个扩展。 2. 接下来,你需要安装OpenCV库。你可以通过以下几种方法之一来安装: - 在Linux上,你可以使用包管理器如apt-get或yum来安装OpenCV。 - 在Windows上,你可以从OpenCV官方网站下载预编译的二进制文件并安装。 3. 安装完成后,打开VS Code并创建一个新的C++项目。你可以选择打开一个现有的项目或者创建一个新的。 4. 在项目文件夹中创建一个名为`.vscode`的文件夹(如果还没有)。 5. 在`.vscode`文件夹中创建一个名为`c_cpp_properties.json`的文件,并将以下内容添加到文件中: ```json { "configurations": [ { "name": "Linux", "includePath": [ "${workspaceFolder}/**", "/usr/local/include" ], "defines": [], "compilerPath": "/usr/bin/g++", "cStandard": "gnu11", "cppStandard": "gnu++14", "intelliSenseMode": "linux-gcc-x64" }, { "name": "Win32", "includePath": [ "${workspaceFolder}/**", "C:/opencv/build/include" ], "defines": [], "compilerPath": "C:/MinGW/bin/g++.exe", "cStandard": "gnu11", "cppStandard": "gnu++14", "intelliSenseMode": "gcc-x64" } ], "version": 4 } ``` 请确保根据你的操作系统和OpenCV的安装位置进行适当的更改。 6. 在VS Code中打开你的C++源文件,并尝试编写和构建代码。如果一切设置正确,你应该能够成功使用OpenCV库。 希望这些步骤对你有所帮助!如果你还有其他问题,请随时提问。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ProfSnail

谢谢老哥嗷

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值