Ubuntu16給python3.5安裝OpenCV3.2

過程略繁瑣,參考了Install OpenCV 3.0 and Python 3.4+ on Ubuntu。安裝完成可在python中import cv2.

#安裝依賴及工具
sudo apt-get install build-essential cmake git pkg-config
sudo apt-get install libjpeg8-dev libtiff4-dev libjasper-dev libpng12-dev
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt-get install libgtk2.0-dev
sudo apt-get install libatlas-base-dev gfortran
sudo apt-get install python3.5-dev

由於我已經有python3.5的virtualenv了,所以這里就不再說了,可以参考pip3为python3安装模块

#啓動python3.5的環境
source ~/pythons/p35/bin/activate
#安装numpy
pip install numpy -i https://pypi.douban.com/simple/
#下載並解壓OpenCV,github我克隆不下拉
cd ~
wget -O opencv.zip https://github.com/Itseez/opencv/archive/3.2.0.zip
unzip opencv.zip
wget -O opencv_contrib.zip https://github.com/Itseez/opencv_contrib/archive/3.2.0.zip
unzip opencv_contrib.zip
cd ~/opencv-3.2.0
mkdir build
cd build
#cmake中間如有終端,可參考錯誤提示直接從web下載相關文件放於提示位置
cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D INSTALL_C_EXAMPLES=OFF \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.2.0/modules \
    -D PYTHON_EXECUTABLE=~/pythons/p35/bin/python \
    -D BUILD_EXAMPLES=ON ..
#成功執行後要留意python3的環境是否正確應有類似如下字樣
--   Python 3:
--     Interpreter:                 /home/42/pythons/p35/bin/python3 (ver 3.5.2)
--     Libraries:                   /usr/lib/x86_64-linux-gnu/libpython3.5m.so (ver 3.5.2)
--     numpy:                       /home/42/pythons/p35/lib/python3.5/site-packages/numpy/core/include (ver 1.12.0)
--     packages path:               lib/python3.5/site-packages
-- 
--   Python (for build):            /home/42/pythons/p35/bin/python3
#然後就可以編譯了
make -j$(nproc)
#編譯完成後執行安裝
sudo make install
sudo ldconfig
#查看是否安裝成功
ls -l /usr/local/lib/python3.5/site-packages/ | grep cv2
#成功的話應該會有文件出現類似
-rw-r--r-- 1 root staff 3550256 2月  17 20:36 cv2.cpython-35m-x86_64-linux-gnu.so
#把cv2關聯到python環境裏
cd ~/pythons/p35/lib/python3.5/site-packages/
ln -s /usr/local/lib/python3.5/site-packages/cv2.cpython-35m-x86_64-linux-gnu.so cv2.so
#查看是否可用
python
>>> import cv2
>>> cv2.__version__
'3.2.0'

你的電子郵件位址並不會被公開。 必要欄位標記為 *