前言
网上WINDOWS系统大多是用CMake+VS安装的OpenCV,但是VS写C/C++太麻烦,而且移植性差,于是笔者决定用MinGW64。相关该博文同时介绍了编译安装存在的问题,笔者将从简介绍步骤
软件环境
- windows10-64bit
- MinGW64-gcc8.1.0
- CMake 3.15.1
- OpenCV 4.1.1
安装步骤
1. 安装CMake+MinGW64
参考,注意添加系统环境变量
2. 下载OpenCV
上下载最新发行版的source文件,下载解压会得到一个"opencv-4.1.1",笔者将其改名为"sources",并移动到"D:SoftwareProOpenCV_MinGW"文件夹下,并同时新建"build"文件夹。
3. 编译OpenCV
打开 CMake-gui,sources和build文件夹配置如下,然后configure
configure一次之后会变成红色,然后勾选WITH_OPENGL和ENABLE_CXX11(OpenCV4之后应该没这个选项),不勾选WITH_IPP、ENABLE_PRECOMPILED_HEADERS和WITH_OPENCL_D3D11_NV,最后configure再generate生成Makefile文件。注意后面安装的头文件和lib文件都会在下图红色线的路径。
4. 安装OpenCV
打开VS Code终端,cd 到D:SoftwareProOpenCV_MinGWuild,然后输入"mingw32-make -j 8"回车设置8线程加快安装速度,然后输入"mingw32-make install"回车安装。安装完毕就可以看到"D:SoftwareProOpenCV_MinGWuildinstall"下如下图
然后新建Path环境变量”D:SoftwareProOpenCV_MinGWuildinstallx64mingwin“。
5. 运行OpenCV实例
笔者在"C:UsersJJ_OMENDesktopProjects est",新建了main.cpp, CMakeLists和build文件夹,并加了名称为"1.jpg"的图片,
main.cpp
#include <opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
cout << "OpenCV Version: " << CV_VERSION << endl;
Mat img = imread("../1.jpg");
imshow("1440", img);
waitKey(0);
return 0;
}
CMakeLists.txt
#设置cmake最低版本
cmake_minimum_required(VERSION 3.2)
#设置项目名称
PROJECT(hello)
#寻找OpenCV库
FIND_PACKAGE(OpenCV REQUIRED)
#打印调试信息
#message(STATUS "version: ${OpenCV_VERSION}")
#cmakemessage(STATUS "OpenCV_INCLUDE_DIRS = ${OpenCV_INCLUDE_DIRS}")
#message(STATUS "OpenCV_LIBS = ${OpenCV_LIBS}")
#message(STATUS "PROJECT_SOURCE_DIR=${PROJECT_SOURCE_DIR}")
#包含项目头文件和OpenCV相关头文件路径
INCLUDE_DIRECTORIES(
${PROJECT_SOURCE_DIR}
#${OpenCV_INCLUDE_DIRS}
#以下路径自行更改
"D:/Software/Pro/OpenCV_MinGW/build/install/include/opencv2"
)
#设置源文件信息
set(SRC
${PROJECT_SOURCE_DIR}/main.cpp
)
#编译可执行程序
ADD_EXECUTABLE(hello ${SRC})
#添加动态链接库
TARGET_LINK_LIBRARIES(hello ${OpenCV_LIBS})
然后在VS Code中CRTL+SHIFT+P输入"c/c++..."找到红色下划线那个
配置如下
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**",
"D:/Software/Pro/OpenCV_MinGW/build/install/include/opencv2/**",
"D:/Software/Pro/OpenCV_MinGW/build/install/include"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"compilerPath": "C:\mingw64\bin\gcc.exe",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "gcc-x64"
},
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"compilerPath": "C:\mingw64\bin\gcc.exe",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "gcc-x64"
}
],
"version": 4
}
重点改的地方如下
也可以进入C/C++ edit configuration (UI)更改,这个自行百度
以上配置好了之后,在终端cd到"C:UsersJJ_OMENDesktopProjects estuild",然后" cmake -G "MinGW Makefiles" ../ "或者"cmake . "生成makefile,然后输入"min" TAB补全"mingw32-make”,然后输入"hello"TAB补全,就可以看到输出结果了。