Ubuntu18.04源码编译OpenCV4.4.0

又一次在Ubuntu18.04下编译OpenCV

官网下载OpenCV4.4.0opencv_contrib的源码就不多说了,依赖库的安装也见官方安装教程

编译过程如下,首先

cd ~/opencv
mkdir build
cd build

接下来按照自己的要求配置OpenCV

cmake -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr/local \
-DOPENCV_GENERATE_PKGCONFIG=ON \
-DOPENCV_EXTRA_MODULES_PATH=/home/xfb/Downloads/opencv_contrib-master/modules \
-DBUILD_DOCS=ON \
-DBUILD_EXAMPLES=ON \
-DINSTALL_C_EXAMPLES=ON \
-DWITH_QT=ON \
-DWITH_GSTREAMER=ON \
-DVIDEOIO_PLUGIN_LIST=gstreamer \
-DOPENCV_ENABLE_NONFREE=ON \
-DBUILD_opencv_python2=OFF \
-DBUILD_opencv_python3=OFF \
-DWITH_LAPACK=ON \
-DWITH_EIGEN=ON \
-DWITH_OPENGL=ON \
-DWITH_CUDA=OFF \
-WITH_CUFFT=OFF \
-DWITH_CUBLAS=OFF \
-DWITH_CUDNN=OFF \
-WITH_NVCUVID=OFF .. 

其中,OPENCV_EXTRA_MODULES_PATHopencv_contrib的下载路径
接下来是正式的编译过程

make -j8

源码编译OpenCV的时候报错:

/usr/bin/ld: /usr/local/lib/libavcodec.a(vc1dsp_mmx.o): relocation R_X86_64_PC32 against symbol `ff_pw_9' 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
modules/videoio/CMakeFiles/opencv_videoio.dir/build.make:289: recipe for target 'lib/libopencv_videoio.so.4.4.0' failed
make[2]: *** [lib/libopencv_videoio.so.4.4.0] Error 1
CMakeFiles/Makefile2:8552: recipe for target 'modules/videoio/CMakeFiles/opencv_videoio.dir/all' failed
make[1]: *** [modules/videoio/CMakeFiles/opencv_videoio.dir/all] Error 2
make[1]: *** Waiting for unfinished jobs....

经过研究,原因是ffmpeg编译安装时没有使用--enable-pic选项,因此又重新源码编译安装了ffmpeg。ffmpeg的源码中提供了安装教程,大致过程为:

./configure --enable-pic
make
sudo make install

ffmpeg重新安装后,重新对OpenCV进行cmake、make,顺利编译通过!
接下来

sudo make install

安装完成后,便可以在IDE中导入OpenCV库了
本人用的IDE是CLion,在Cmakelist中加入OpenCV

# OpenCV
set(OpenCV_DIR "/usr/local/lib/cmake/opencv4") # 设置OpenCVConfig.cmake文件的路径
find_package(OpenCV REQUIRED)

target_link_libraries(项目名 ${OpenCV_LIBS})

代码中可以成功导入OpenCV的库了
Ubuntu18.04源码编译OpenCV4.4.0_第1张图片


2020-8-11更新
上述方式安装之后,发现OpenCV依旧无法通过ffmpeg底层调用摄像头,因此又做了调研。
根据https://github.com/opencv/opencv/issues/10217,需要在源码编译ffmpeg时手动指定安装的路径,否则OpenCV无法找到安装好的ffmpeg库。
更新后的ffmepg配置指令为:

./configure --enable-pic --prefix=/usr/local --libdir=/usr/local/lib 

此外,上述issue中还提到,加上ffmepg模块时,OpenCV可能不能采用动态编译,本人尝试后发现make OpenCV时会出现和未添加--enable-pic时同样的错,而静态编译则顺利通过。不知有没有方法解决动态编译的问题,恳请各位大佬路过时不吝赐教。

你可能感兴趣的:(Ubuntu,工具配置)