项目场景:
Win10下 QT Creator配置opencv库文件:
环境描述:
QT Creator版本:4.11.1
opencv库文件:4.1.0
原因分析:
由于opencv的库文件一般是dll动态链接库文件,可以被MSVC(Visual studio编译器所编译引用),但QT一般采用的是MinGw编译器,所以要引用opencv的动态链接库需要通过Cmake编译器转换一下。下列步骤可以成功在QT creator中配置opencv库文件解决方案:
默认已在win10中下载好QT,并安装相应的MinGw32和64编译器,并添加了相应MInGW的系统变量,根据自己QT中的MinGW路径自行添加,主要添加后两个。正常情况下是需要下载cmake对opencv文件进行编译转换,但下面网站中已经有各个版本的opencv的MinGw的编译文件,省去自己下载cmake将opencv文件编译转换了。
链接: https://codechina.csdn.net/mirrors/huihut/opencv-mingw-build?utm_source=csdn_github_accelerator.
点击configuration查看编译环境,下载相应版本的.zip即可
我下的是OpenCV-MinGW-Build-OpenCV-4.1.0,放在D:\中
将D:\OpenCV-MinGW-Build-OpenCV-4.1.0\x86\mingw\bin添加进系统变量Path中
新建QT widget项目,一路默认,在QT项目栏的配置文件.pro中添加,如下:
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked 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 it uses 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
FORMS += \
mainwindow.ui
TRANSLATIONS += \
QT_MultipleVision_zh_CN.ts
INCLUDEPATH += D:\OpenCV-MinGW-Build-OpenCV-4.1.0\include\
D:\OpenCV-MinGW-Build-OpenCV-4.1.0\include\opencv2\
D:\OpenCV-MinGW-Build-OpenCV-4.1.0\include\opencv
LIBS += D:\OpenCV-MinGW-Build-OpenCV-4.1.0\x86\mingw\lib\libopencv_*.a
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
在main.cpp源文件中添加 #include "opencv2/opencv.hpp"
以及下述代码进行OpenCV成功配置的验证
cv::Mat image = imread("C:\\Users\\admin\\Desktop\\J30J.jpg");
namedWindow("Display window",WINDOW_AUTOSIZE);
imshow("Display window",image);
waitKey();
// main.cpp
#include "mainwindow.h"
#include <QApplication>
#include "opencv2/opencv.hpp"
using namespace cv;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
cv::Mat image = imread("C:\\Users\\admin\\Desktop\\J30J.jpg");
namedWindow("Display window",WINDOW_AUTOSIZE);
imshow("Display window",image);
waitKey();
MainWindow w;
w.show();
return a.exec();
}
代码中图片路径根据自己实际情况进行编写,然后点击小锤子进行编译,然后运行。
结果会弹出你所设置路径下的图片,至此QT Creator的OpenCV库文件配置完成
如出现error: undefined reference to
之类的错误,可以尝试将QT项目文件夹下的Debug文件夹、Release文件夹删除,然后进行重新编译,QT的debug构建Kit选择MinGw32 bit