1. 编译静态库
- 拉取opencv源码:
https://github.com/opencv/opencv.git - 进入源码根目录,在platforms/linux目录下创建编译脚本build_linux.sh
cd platforms/linux
vi build_linux.sh
脚本里配置cmake编译参数,这里编译静态库需要将
-DBUILD_SHARED_LIBS=OFF
如果-DBUILD_opencv_world=ON,所有静态库会集中在一个opencv_world里。
可以根据自己的需求打开或关闭对应的开关。
#!/bin/bash
BUILD_TYPE='Release'
rm -rf build_linux
mkdir build_linux
cd build_linux
cmake ../../../ \
-DCMAKE_BUILD_TYPE=RELEASE \
-DBUILD_opencv_python2=OFF \
-DBUILD_opencv_python3=OFF \
-DBUILD_SHARED_LIBS=OFF \
-DBUILD_opencv_java=OFF \
-DBUILD_opencv_world=ON \
-DBUILD_JAVA=OFF \
-DBUILD_ANDROID_EXAMPLES=OFF \
-DWITH_OPENCL=OFF \
-DWITH_IPP=OFF \
-DWITH_TBB=OFF \
-DBUILD_EXAMPLES=OFF \
-DBUILD_TESTS=OFF \
-DBUILD_PERF_TESTS=OFF \
-DBUILD_DOCS=OFF
make -j8
这里我们只编译不安装,如果要安装,需要执行make install。
- 编译完成后,在build_linux/lib和build_linux/3rdparty/lib下面产生静态库,都是需要的。
2. 链接及测试
为了检查静态库能否正常使用,搭建了简单的cmake测试工程
- 把头文件和编译好的制品库拷贝到测试工程下
- 添加测试代码test.cpp
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
int main() {
cv::Mat image = cv::imread("your_dir/IMG_1811.JPG", cv::IMREAD_COLOR);
if (image.empty()) {
cerr << "Failed to read image" << endl;
return -1;
}
return 0;
}
- 添加cmakelist.txt, 注意:
- 除了添加opencv_world还要添加3rdparty的那几个依赖库;
- target_link_library()要加上-lz, -ldl两个选项;
cmake_minimum_required(VERSION 3.10)
project(OpenCVTest)
message("project root path is ${CMAKE_CURRENT_SOURCE_DIR}")
set(CMAKE_CXX_FLAGS "-pthread" )
set(ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
set(OPENCV_LIB_PATH "${CMAKE_CURRENT_SOURCE_DIR}/libs/linux/x86-64")
macro(OPENCV_IMPORT_LIBS LibsList LibName LibPaths)
message(STATUS "import libs ${LibName}!")
add_library(${LibName} STATIC IMPORTED GLOBAL)
set_target_properties(${LibName} PROPERTIES IMPORTED_LOCATION ${LibPaths})
list(APPEND ${LibsList} ${LibName})
endmacro(OPENCV_IMPORT_LIBS LibsList LibName LibPaths)
include_directories(${ROOT_PATH}/include)
OPENCV_IMPORT_LIBS(OPENCV_LIBS opencv_world "${OPENCV_LIB_PATH}/libopencv_world.a")
OPENCV_IMPORT_LIBS(OPENCV_LIBS opencv_llmlmf "${OPENCV_LIB_PATH}/libIlmImf.a")
OPENCV_IMPORT_LIBS(OPENCV_LIBS opencv_libjpeg "${OPENCV_LIB_PATH}/liblibjpeg-turbo.a")
OPENCV_IMPORT_LIBS(OPENCV_LIBS opencv_libpng "${OPENCV_LIB_PATH}/liblibpng.a")
OPENCV_IMPORT_LIBS(OPENCV_LIBS opencv_libtiff "${OPENCV_LIB_PATH}/liblibtiff.a")
OPENCV_IMPORT_LIBS(OPENCV_LIBS opencv_libjasper "${OPENCV_LIB_PATH}/liblibjasper.a")
OPENCV_IMPORT_LIBS(OPENCV_LIBS opencv_libnotify "${OPENCV_LIB_PATH}/libittnotify.a")
OPENCV_IMPORT_LIBS(OPENCV_LIBS opencv_libwebp "${OPENCV_LIB_PATH}/liblibwebp.a")
file(GLOB_RECURSE WRAPPER_SRCS
${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp
)
add_executable(OpenCVTest ${WRAPPER_SRCS})
target_link_libraries(OpenCVTest
${OPENCV_LIBS}
-lz
-ldl
)
- 编译
在工程根目录下创建build.sh脚本
#!/bin/bash
if [ -d "build" ]; then
echo "clean build dir... "
rm -rf build
fi
mkdir build
cd build
cmake ..
make
- 测试
如果上一步没有问题,进入build目录,run可执行文件即可
cd build
./OpencvTest
如果没有报错就可以了。