在一个只有ubuntu20.04的docker环境中配置opencv4.0.0,
什么库都没有,都要重新安装,
其他的问题在网上都找到了解决方案,唯独这个问题比较棘手:
[ 86%] Linking CXX executable .../.../bin/opencv_annotation
/usr/bin/ld: /usr/local/lib/libgflags.a(gflags.cc.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: bad value
collect2: error: ld returned 1 exit status
make[2]: [modules/sfm/CMakeFiles/opencv_sfm.dir/build.make:243: lib/libopencv_sfm.so.4.0.0] Error 1
make[1]: [CMakeFiles/Makefile2:12239: modules/sfm/CMakeFiles/opencv_sfm.dir/all] Error 2
我看出是编译libopencv_sfm.so时出的问题,也看出需要用-fPIC重新编译gflags
bash
# 1. 首先清理之前的安装
sudo apt remove libgflags-dev
cd ~/gflags
rm -rf build
cmake -DCMAKE_BUILD_TYPE=Release \
-DBUILD_SHARED_LIBS=ON \
-DCMAKE_CXX_FLAGS="-fPIC" \
-DCMAKE_C_FLAGS="-fPIC" \
-DCMAKE_INSTALL_PREFIX=/usr/local \
..
# 3. 编译和安装
make -j$(nproc)
sudo make install
sudo ldconfig
编译好之后再重新build opencv,
注意我是在root权限下,不是root的前面都加上sudo
bash
cd ~/opencv/build
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local/opencv4.0.0 -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-4.0.0/modules -D BLAS_LIBRARIES=/usr/lib/x86_64-linux-gnu/libblas.so -D LAPACK_LIBRARIES=/usr/lib/x86_64-linux-gnu/liblapack.so ..
make -j8
make install
#更新系统的动态链接库缓存
ldconfig
sudo nano ~/.bashrc
# 在文件末尾添加以下内容
# 根据自己的安装路径来,我是cmake时指定了安装在/usr/local/opencv4.0.0
export OpenCV_DIR=/usr/local/opencv4.0.0
export PATH=$PATH:$OpenCV_DIR/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$OpenCV_DIR/lib
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$OpenCV_DIR/lib/pkgconfig
export CPATH=$CPATH:$OpenCV_DIR/include/opencv4
# 保存并退出(在nano中按Ctrl+X,然后按Y确认,最后按Enter)
#用vi也行
# 使环境变量生效
source ~/.bashrc
为了确保pkg-config能正确找到OpenCV,还需要创建或修改pkg-config文件:
bash
# 如果pkg-config文件夹不存在,创建它
sudo mkdir -p /usr/local/opencv4.0.0/lib/pkgconfig
# 创建opencv4.pc文件
sudo nano /usr/local/opencv4.0.0/lib/pkgconfig/opencv4.pc
#添加以下内容
prefix=/usr/local/opencv4.0.0
exec_prefix=${prefix}
includedir=${prefix}/include
libdir=${prefix}/lib
Name: OpenCV
Description: Open Source Computer Vision Library
Version: 4.0.0
Cflags: -I${includedir}
Libs: -L${libdir} -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_ml -lopencv_video -lopencv_features2d -lopencv_calib3d -lopencv_objdetect -lopencv_flann
最后验证安装:
bash
# 检查环境变量是否设置成功
echo $LD_LIBRARY_PATH
echo $PKG_CONFIG_PATH
# 检查OpenCV是否能被找到
pkg-config --modversion opencv4