How to build opencv-python如何本地编译OpenCV的Python版本

创建Python环境

我使用的是virtualenv创建的环境,如果你使用conda也是同理,这两个我都测试过。

virtualenv --system-site-packages -p python3  ~/pyenv/tf1x

启动刚刚创建的环境

source ~/pyenv/tf1x/bin/activate

安装OpenCV的Python依赖库

pip install numpy

开始编译OpenCV

我使用的OpenCV4.1.0版本我在3.4.x版本也测试过,同样可以执行

(tf1x) king@king-desktop:~/source/opencv-4.1.0$ 这里是起始目录
mkdir build  
cd build
cmake   -D CMAKE_BUILD_TYPE=RELEASE \
    -D PYTHON_DEFAULT_EXECUTABLE=$(python -c "import sys; print(sys.executable)")   \
    -D PYTHON3_EXECUTABLE=$(python -c "import sys; print(sys.executable)")   \
    -D PYTHON3_NUMPY_INCLUDE_DIRS=$(python -c "import numpy; print (numpy.get_include())") \
    -D PYTHON3_PACKAGES_PATH=$(python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \
    -D CMAKE_CXX_FLAGS="-std=c++11" \
    -D CUDA_NVCC_FLAGS="--compiler-options "-std=c++03"" ..

查看输出打印

大家看到了吗?python2python3都检查出来了,python2是系统默认的,python3是我们创建的,通过python所在目录就可以辨别出来。

--   Python 2:
--     Interpreter:                 /usr/bin/python2.7 (ver 2.7.15)
--     Libraries:                   /usr/lib/x86_64-linux-gnu/libpython2.7.so (ver 2.7.15+)
--     numpy:                       /home/king/.local/lib/python2.7/site-packages/numpy/core/include (ver 1.16.4)
--     install path:                lib/python2.7/dist-packages/cv2/python-2.7
-- 
--   Python 3:
--     Interpreter:                 /home/king/pyenv/tf1x/bin/python (ver 3.6.8)
--     Libraries:                   /usr/lib/x86_64-linux-gnu/libpython3.6m.so (ver 3.6.8)
--     numpy:                       /home/king/pyenv/tf1x/lib/python3.6/site-packages/numpy/core/include (ver 1.16.4)
--     install path:                /home/king/pyenv/tf1x/lib/python3.6/site-packages/cv2/python-3.6
-- 
--   Python (for build):            /home/king/pyenv/tf1x/bin/python

编译安装

字母j后面的数字根据自身CPU支持的线程数来确定。

make -j12 
sudo make install

安装摘要

下面的几句话表示python2python3的编译成功和安装成功。

[ 99%] Built target opencv_python2
[ 99%] Built target opencv_python3

-- Set runtime path of "/usr/local/lib/python2.7/dist-packages/cv2/python-2.7/cv2.so" to "/usr/local/lib"
-- Set runtime path of "/home/king/pyenv/tf1x/lib/python3.6/site-packages/cv2/python-3.6/cv2.cpython-36m-x86_64-linux-gnu.so" to "/usr/local/lib"

运行测试

没有报错就是OK了

(tf1x) king@king-desktop:~/source/opencv-4.1.0/build$ python
Python 3.6.8 (default, Jan 14 2019, 11:02:34) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> print("OpenCV Version : ", cv2.__version__)
OpenCV Version :  4.1.0
>>> exit()


你可能感兴趣的:(Python,Linux)