12-Qt5调用OpenCV4

QT5调用OpenCV4

利用前面已经编译好的opencv4,我们下面将调用opencv4进行使用。

  • QT导入OpenCV4

    可以参照前面导入GSL的例子,首先我们制作一个包含OpenCV相关文件的文件夹(make install之后默认安装在install文件夹)

    • 制作pri文件

      # 宏定义项,指明采用OPENCV
      
      DEFINES += OPENCV4_DLL
      
      # 指明GSL库所对应的头文件所在目录
      INCLUDEPATH += $$PWD/include
      
      # 链接静态库
      #CONFIG += static
      # 指明依赖库关系
      LIBS += $$PWD/lib/libopencv_calib3d411.dll.a
      LIBS += $$PWD/lib/libopencv_core411.dll.a
      LIBS += $$PWD/lib/libopencv_dnn411.dll.a
      LIBS += $$PWD/lib/libopencv_features2d411.dll.a
      LIBS += $$PWD/lib/libopencv_flann411.dll.a
      LIBS += $$PWD/lib/libopencv_gapi411.dll.a
      LIBS += $$PWD/lib/libopencv_highgui411.dll.a
      LIBS += $$PWD/lib/libopencv_imgcodecs411.dll.a
      LIBS += $$PWD/lib/libopencv_imgproc411.dll.a
      LIBS += $$PWD/lib/libopencv_ml411.dll.a
      LIBS += $$PWD/lib/libopencv_objdetect411.dll.a
      LIBS += $$PWD/lib/libopencv_photo411.dll.a
      LIBS += $$PWD/lib/libopencv_stitching411.dll.a
      LIBS += $$PWD/lib/libopencv_video411.dll.a
      LIBS += $$PWD/lib/libopencv_videoio411.dll.a
      
    • 新建qt工程进行测试

      需要将opencv4文件夹放置工程目录下

      • 配置pro文件,导入opencv4.pri

      • 测试代码

        #include 
        #include 
        #include 
        using namespace std;
        using namespace cv;
        
        int main()
        {
            cv::Mat image = cv::imread("F:\\opencv-4.1.1\\doc\\opencv.jpg", IMREAD_COLOR);
            if (image.empty())
                printf("读取图片错误!");
            // create image window named "My Image"
            cv::namedWindow("My Image", WINDOW_AUTOSIZE);
            // show the image on window
            cv::imshow("My Image", image);
            cv::waitKey(0);
        }
        
      • 编译运行:
        g++ test.cpp -I"E:\ScientificComputing\opencv4_install\include" -L"E:\ScientificComputing\opencv4_install\lib" -llibopencv_core420 -llibopencv_dnn420 -llibopencv_highgui420 -llibopencv_imgcodecs420 -llibopencv_imgproc420 -llibopencv_objdetect420 -llibopencv_video420 -llibopencv_videoio420 -llibopencv_features2d420 -llibopencv_calib3d420 -llibopencv_gapi420 -llibopencv_photo420 -llibopencv_flann420
        发现程序异常结束,进入生成程序所在目录进行查看,命令行执行,发现找不到动态库,

      • 添加opencv4动态库路径至系统环境变量(重启软件),或者拷贝至程序所在同级目录

测试发现opencv只能以动态库的形式进行使用,如果需要生成静态库,cmake需要指定参数-DBUILD_SHARED_LIBS=0

如果小伙伴们对文章内容有不理解的地方可以查看博主制作的相对应视频教程哦:
https://www.bilibili.com/video/av64273096

你可能感兴趣的:(Qt)