1. 程式人生 > >ubuntu編譯安裝opencv3到anaconda虛擬環境(virtual env同理)

ubuntu編譯安裝opencv3到anaconda虛擬環境(virtual env同理)

背景

最近在做視訊的物體追蹤,要用到視訊讀取函式和Tracker類,在pip conda安裝的cv2中都沒有。只好自己DIY安裝Opencvanaconda中。

Step 1 安裝需要的庫.

sudo apt-get install cmake gcc g++ git libjpeg-dev libpng-dev libtiff5-dev libavcodec-dev libavformat-dev libswscale-dev pkg-config libgtk2.0-dev libopenblas-dev libatlas-base-dev liblapack-dev libeigen3-dev libtheora-dev libvorbis-dev libxvidcore-dev libx264-dev sphinx-common libtbb-dev yasm libopencore-amrnb-dev libopencore-amrwb-dev libopenexr-dev libgstreamer-plugins-base1.0-dev libavcodec-dev libavutil-dev libavfilter-dev libavformat-dev libavresample-dev ffmpeg

Step 2 啟用虛擬環境

啟用自己的虛擬環境:

source activate virenv_name

提前裝好numpy(想必已有)

Step 3 下載好opencv 原始碼

包括opencv 3.x.x.zip, opencv_contrib-3.x.x.zip(做視訊類的應該需要)

新建構建資料夾

cd opencv3.x.x
mkdir build
cd ./build

Step 4 CMake 配置

cmake -D CMAKE_BUILD_TYPE=Release -D INSTALL_PYTHON_EXAMPLES=ON -D INSTALL_C_EXAMPLES=OFF -D BUILD_EXAMPLES=ON -D OPENCV_EXTRA_MODULES_PATH=/home/amax/Downloads/opencv/opencv_contrib-3.3.1/modules -D CMAKE_LIBRARY_PATH=/usr/local/cuda-8.0/lib64/stubs -D WITH_CUDA=ON -DBUILD_TIFF=ON -DBUILD_opencv_java=OFF -DWITH_OPENGL=ON -DWITH_OPENCL=ON -DWITH_IPP=ON -DWITH_TBB=ON -DWITH_EIGEN=ON -DWITH_V4L=ON -DWITH_VTK=OFF -DBUILD_TESTS=OFF -DBUILD_opencv_dnn=ON -D CUDA_NVCC_FLAGS="-D_FORCE_INLINES --expt-relaxed-constexpr" -DBUILD_LIBPROTOBUF_FROM_SOURCES=ON -DBUILD_PERF_TESTS=OFF -DCMAKE_INSTALL_PREFIX=$(python -c "import sys; print(sys.prefix)") -DPYTHON3_EXECUTABLE=$(which python) -DPYTHON_INCLUDE_DIR=$(python -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") -DPYTHON_PACKAGES_PATH=$(python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") -DPYTHON3_NUMPY_INCLUDE_DIRS=$(python -c "import numpy; import os; print(os.path.join(numpy.__path__[0], 'core', 'include'))") -DPYTHON_LIBRARY=/home/amax/anaconda3/envs/rootclone/lib/libpython3.5m.so .. 

命令中的目錄自行修改。如果是python2的,需要將上面的DPYTHON3_*替換為DPYTHON2_*

此步後記:

中間配置遇到的問題:C++編譯器配置有問題,cmake自動使用了anaconda2(我本anaconda3)C++編譯器,導致後續的make出錯(Makefile:160: recipe for target 'all' failed)。

解決方法:

1.方案一:解除虛擬環境(source deactivate),使用系統的python環境安裝(此時,系統會切換到urs/bin/cc編譯)。再啟用虛擬環境,cmake,即可找到/usr/bin/cc作為虛擬環境Opencv的編譯器。

2.方案二:使用cmake選項指定編譯器路徑,-DCMAKE_C_COMPILER=/usr/bin/cc -DCMAKE_CXX_COMPILER=/usr/bin/c++ 

Step 5. make & install 

make -j10  #10執行緒並行編譯,核多的大佬可以多用幾個
make install

Step 6. 試驗

python

import cv2

如果報錯:libstdc++.so.6: version `GLIBCXX_3.*.*' not found,請升級libgcc

conda install libgcc


參考連結:

https://docs.opencv.org/master/d7/d9f/tutorial_linux_install.html

https://www.scivision.co/anaconda-python-opencv3/