VScode編譯opencv(Cmake + MinGW)

文森88發表於2020-12-17

1.環境搭建

1.MinGW
2.已經編譯的opencv,網上搜尋OpenCV-MinGW-Build-OpenCV-4.1.1-x64下載即可
3.VS code的外掛 Cmake tools

2.Cmake編譯檔案

CMakeLists.txt檔案如下:

cmake_minimum_required(VERSION 3.0.0)
project(isp VERSION 0.1.0)

include(CTest)
enable_testing()

#設定平臺 x86
set(platform x86)

#標頭檔案
set(OpenCV_INCLUDE_DIRS H:/project/algo/opencv/OpenCV-MinGW-Build-OpenCV-4.1.1-x64/include/)
include_directories(./ ./core ${OpenCV_INCLUDE_DIRS})

# 新增子目錄
#add_subdirectory(core) 子目錄需要有CMakeList.txt

# 新增資料夾及其檔案,自動新增資料夾中的檔案
aux_source_directory(. DIRSRCS)
add_executable(isp ${DIRSRCS})

#################################################opencv 部分 方式1 find #####################################
#指定OpenCV版本,程式碼如下
#find_package(OpenCV 3.3 REQUIRED)
#如果不需要指定OpenCV版本,程式碼如下

#set(CMAKE_MODULE_PATH  H:\\project\\algo\\opencv\\OpenCV-MinGW-Build-OpenCV-3.4.5\\x86\\mingw\\lib\\)
#set(OpenCV_DIR H:\\project\\algo\\opencv\\OpenCV-MinGW-Build-OpenCV-3.4.5\\x86\\mingw\\lib\\)
#find_package(OpenCV REQUIRED)

#顯示OpenCV_INCLUDE_DIRS的值
#message(${OpenCV_INCLUDE_DIRS})

# 新增一個可執行程式
# 語法:add_executable( 程式名 原始碼檔案 )
#add_executable( isp ${DIRSRCS} )

# 將庫檔案連結到可執行程式上
#target_link_libraries( isp  ${OpenCV_LIBS})
#################################################opencv 部分 方式2 #####################################
# 依賴庫
# 尋找OpenCV庫
set(OpenCV_DIR H:/project/algo/opencv/OpenCV-MinGW-Build-OpenCV-4.1.1-x64/x64/mingw/bin/)

SET(CMAKE_FIND_LIBRARY_PREFIXES "")
SET(CMAKE_FIND_LIBRARY_SUFFIXES ".lib" ".dll")
set(CMAKE_MODULE_PATH  ${OpenCV_DIR})
set(CMAKE_PREFIX_PATH ${OpenCV_DIR})

# 連結OpenCV庫路徑
link_directories(${OpenCV_DIR})

#find_library(OpenCV_LIBS libopencv_core411 ${OpenCV_DIR} ) libopencv_imgproc411

find_library(OpenCV_LIBS1
    NAMES libopencv_core411
    PATHS ${OpenCV_DIR}
    NO_DEFAULT_PATH)

find_library(OpenCV_LIBS
    NAMES libopencv_imgproc411
    PATHS ${OpenCV_DIR}
    NO_DEFAULT_PATH)

find_library(OpenCV_LIBS2
    NAMES libopencv_imgcodecs411
    PATHS ${OpenCV_DIR}
    NO_DEFAULT_PATH)

find_library(OpenCV_LIBS3
    NAMES libopencv_highgui411
    PATHS ${OpenCV_DIR}
    NO_DEFAULT_PATH)

#message(STATUS "test")
message("${OpenCV_LIBS}")
message("${OpenCV_LIBS1}")
message("${OpenCV_LIBS2}")
# 連結OpenCV庫
#SET(CMAKE_EXE_LINKER_FLAGS " -no-pie")

target_link_libraries(isp ${OpenCV_LIBS} ${OpenCV_LIBS1} ${OpenCV_LIBS2} ${OpenCV_LIBS3})

set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)

H:/project/algo/opencv/OpenCV-MinGW-Build-OpenCV-4.1.1-x64/ 為在網上下載的已經編譯好的Opencv。

C++程式碼:

using namespace std;
using namespace cv;
#include <opencv2/opencv.hpp>
    Mat img =imread("main.jpg");
    imshow("image",img);
    waitKey();

總結

主要難點在於CmakeList檔案的配置,有不少的坑。
1.必須逐個的find_library,再 target_link_libraries。

相關文章