在Linux上静态编译OpenCV的详细步骤
1. 准备工作
(图片来源网络,侵删)
确保你的系统已经安装了必要的工具和依赖项,可以使用以下命令进行安装:
sudo apt-get update sudo apt-get install build-essential cmake git
2. 获取OpenCV源码
从GitHub上克隆OpenCV的源代码:
git clone https://github.com/opencv/opencv.git cd opencv
3. 创建构建目录并配置CMake
在OpenCV源码根目录下创建一个用于构建的目录,并进入该目录:
(图片来源网络,侵删)
mkdir build && cd build
使用CMake生成Makefile文件时,需要设置一些参数以编译静态库,以下是关键参数的解释:
-DBUILD_SHARED_LIBS=OFF
: 禁用共享库,只编译静态库。
-DBUILD_opencv_world=ON
: 将所有静态库集中到一个名为opencv_world
的静态库中。
-DWITH_*=OFF
: 根据需求关闭不需要的功能模块。
完整的CMake配置命令如下:
(图片来源网络,侵删)
cmake ../ -DCMAKE_BUILD_TYPE=RELEASE -DBUILD_SHARED_LIBS=OFF -DBUILD_opencv_python2=OFF -DBUILD_opencv_python3=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
4. 编译和安装
执行以下命令进行编译:
make -j8 # 这里的数字8表示使用8个CPU核心进行并行编译,可以根据实际情况调整
编译完成后,可以选择安装OpenCV:
sudo make install
5. 验证和使用静态库
为了验证静态库是否正常工作,可以创建一个简单的测试项目,以下是一个简单的CMakeLists.txt示例:
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 "Importing libs ${LibName}!") add_library(${LibName} STATIC IMPORTED GLOBAL) set_target_properties(${LibName} PROPERTIES IMPORTED_LOCATION ${LibPaths}) list(APPEND ${LibsList} ${LibName}) endmacro() 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") add_executable(OpenCVTest test.cpp) target_link_libraries(OpenCVTest ${OPENCV_LIBS} -lz -ldl)
然后编写一个简单的测试程序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; }
编译并运行测试程序:
mkdir build && cd build cmake .. make ./OpenCVTest
如果程序能够正确读取并显示图像,则说明OpenCV静态库配置成功。
小伙伴们,上文介绍linux静态编译opencv的内容,你了解清楚吗?希望对你有所帮助,任何问题可以给我留言,让我们下期再见吧。
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/83240.html