这是一个复杂且漫长的过程。网上找了许多文章,最后发现最好的文章就是Qt官网的帮助文档。
链接:https://wiki.qt.io/How_to_setup_Qt_and_openCV_on_Windows
第一步,下载安装Qt、cmake、解压OpenCV
第二步:添加环境变量
添加完成后重启电脑使环境变量生效。
第三步,打开cmake,用cmake编译openCV源码。分别设置源码目录和build目录,设置完成后Configure
configure过程中发现一直在下载opencv_ffmpeg.dll,而我的电脑没有联网,于是下载一个。下载方法参考:
http://blog.csdn.net/qq_38880380/article/details/78013056,然后重新Configure。这个过程有点长。
第四步:Configure完成后会出现很多红色的,勾选上with QT和WITH OPENGL,再次Configure,直达没有红色的,点Generate。
第五步:打开openCV的build目录,我的是C:\OpenCV\Install,在此路径下打开cmd,输入mingw32-make命令。可以添加参数-j 8 j
表示多线程编译8代表你的CPU核心数可以更高。
这一步就开始报错了。参考官网文档
... windres.exe: unknown option -- W ...
ENABLE_PRECOMPILED_HEADERS
pencv/sources/modules/videoio/src/cap_dshow.cpp
pencv/sources/modules/videoio/src/cap_dshow.cpp
文件中 #include "DShow.h"
前 #define NO_DSHOW_STRSAFE
修改完这两个问题后,重复上面的步骤,记得Configure前清除缓存。
然后编译通过。
第六步,输入命令mingw32-make install,安装成功。
至此配置完成,可以编程测试一下。
pro文件
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = openCVtest
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
INCLUDEPATH += C:\OpenCV\Install\install\include
LIBS += C:\OpenCV\Install\install\x86\mingw\lib\libopencv_*.a
FORMS += \
mainwindow.ui
mainwindow.cpp文件
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include
#include
#include
#include
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// read an image
cv::Mat image = cv::imread("D://QtJob/openCVtest/1.jpg");
// create image window named "My Image"
cv::namedWindow("My Image");
// show the image on window
cv::imshow("My Image", image);
}
MainWindow::~MainWindow()
{
delete ui;
}
运行效果如下