4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

OpenCVAdvent Calendar 2023

Day 5

pyenvに花束を ~任意バージョンのpythonでOpenCV bindingを~

Last updated at Posted at 2023-12-04

この記事はOpenCV Advent Calendar 2023の5日目の記事です。
他の記事は目次にまとめられています。

pyenvセットアップは、@koooooo氏のpyenvのインストール、使い方、pythonのバージョン切り替えできない時の対処法 を参考にさせていただいております。

■ TL;DR: pyenv + OpenCVでもっと自由に!

  • 任意バージョンをインストールするのに、pyenvが便利です
  • OpenCVでpyenv使うには、ちょっと工夫(コマンドライン引数)が必要
  • これで古いlinuxでも最新python, opencvが活用できますね!

■ おはなしのはじまり

OpenCVのissue trackerで、「pyenvと組み合わせたら、上手く動かないんだけど」とのコメントあり。ということで試してみた。

◯何がうれしいのか?

例えば、ubuntuの場合、1 versionに1種類のpythonしか入っていない。下記は執筆時(11/4)のバージョン ( パッケージ:python3-dev などで確認)

これ以外のバージョンを使いたい/最新版のpythonを使いたい/せっかくだから俺はこのPython3.12を選ぶぜ するには、pyenvが必要になる。

version Release Python3
focal 20.04LTS 3.8.2
jammy 22.04LTS 3.10.6
lunar 23.04 3.11.2
mantic 23.10 3.11.4
noble 24.04 3.11.4

■ ためしてみよう

それでは、順番を追って試していく。

◯必要なプログラムをインストール

作業開始に先立ち、必要なプログラムをapt installしておく。

なお、ccache/ninja-build/ cmake-curses-gui は趣味!

sudo apt update -y
sudo apt install -y build-essential \
                    curl \
                    git \
                    cmake \
                    ccache \
                    ninja-build \
                    libffi-dev \
                    libssl-dev \
                    zlib1g-dev \
                    liblzma-dev \
                    libbz2-dev \
                    libreadline-dev \
                    libsqlite3-dev \
                    libncurses5-dev

◯作業フォルダを作成

作業フォルダを、/home/XXXX/work にしておく。

cd 
mkdir work
cd work

◯pyenv環境を構築

pyenv実行に必要なプログラムをgit cloneし、環境変数にセット。

git clone https://github.com/pyenv/pyenv.git ~/.pyenv
echo '' >> ~/.bashrc
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init --path)"' >> ~/.bashrc
source ~/.bashrc

◯python 3.12.0を入れてみる

pyenvでpython 3.12はあるかな、とおもって確認したら、しっかりありますねえ…

kmtr@kmtr-None:~/work$ pyenv install --list | grep 3.12
  3.12.0
  3.12-dev
  pypy2.7-7.3.12-src
  pypy2.7-7.3.12
  pypy3.9-7.3.12-src
  pypy3.9-7.3.12
  pypy3.10-7.3.12-src
  pypy3.10-7.3.12
 

python 3.12.0を入れてみる。

# install python
pyenv install 3.12.0
pyenv global  3.12.0

◯numpyもインストールする

今使っているpython3に、numpyも入れる。なお、もしget-pip.pyを実行したときに、python2なんぞ知らん!と怒られたら、python3.12 get-pip.py にコマンドを置き換えるべきかも。which pythonをちぇけらございます。

# install pip and numpy
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
pip install numpy

◯OpenCVをbuildする

それではさっそく、OpenCVをbuildしていく!

git clone https://github.com/opencv/opencv.git
cmake -D OPENCV_PYTHON3_INSTALL_PATH=$(pyenv exec python3 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \
      -D PYTHON_EXECUTABLE=$(pyenv which python3) \
      -D PYTHON_INCLUDE_DIR=$(pyenv exec python3 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \
      -D PYTHON_LIBRARY=$(pyenv exec python3 -c "from distutils.sysconfig import get_config_var;from os.path import dirname,join ; print(join(dirname(get_config_var('LIBPC')),get_config_var('LDLIBRARY')))") \
      -D PYTHON3_NUMPY_INCLUDE_DIRS=$(pyenv exec python3 -c "import numpy; print(numpy.get_include())") \
      -D PYTHON3_PACKAGES_PATH=$(pyenv exec python3 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \
      -S opencv \
      -B build4-main_python3.12.0 \
      -G Ninja

cmakeコマンドの結果、ばっちりpython3.12.0でopencv python3 moduleが有効化されている!大勝利確定フラグでございます。


--   OpenCV modules:
--     To be built:                 calib3d core dnn features2d flann gapi highgui imgcodecs imgproc ml objdetect photo python3 stitching ts video videoio

--   Python 3:
--     Interpreter:                 /home/kmtr/.pyenv/shims/python3 (ver 3.12)
--     Libraries:                   /home/kmtr/.pyenv/versions/3.12.0/lib/libpython3.12.so (ver 3.12.0)
--     numpy:                       /home/kmtr/.pyenv/versions/3.12.0/lib/python3.12/site-packages/numpy/core/include (ver 1.26.1)
--     install path:                /home/kmtr/.pyenv/versions/3.12.0/lib/python3.12/site-packages/cv2/python-3.12
--
--   Python (for build):            /home/kmtr/.pyenv/shims/python3
参考情報:cmakeコマンド結果 全文
-- General configuration for OpenCV 4.8.0-dev =====================================
--   Version control:               4.8.0-365-ge95c0055af
--
--   Platform:
--     Timestamp:                   2023-11-03T23:28:13Z
--     Host:                        Linux 6.5.0-10-generic x86_64
--     CMake:                       3.27.4
--     CMake generator:             Ninja
--     CMake build tool:            /usr/bin/ninja
--     Configuration:               Release
--
--   CPU/HW features:
--     Baseline:                    SSE SSE2 SSE3
--       requested:                 SSE3
--     Dispatched code generation:  SSE4_1 SSE4_2 FP16 AVX AVX2 AVX512_SKX
--       requested:                 SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX
--       SSE4_1 (18 files):         + SSSE3 SSE4_1
--       SSE4_2 (2 files):          + SSSE3 SSE4_1 POPCNT SSE4_2
--       FP16 (1 files):            + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 AVX
--       AVX (9 files):             + SSSE3 SSE4_1 POPCNT SSE4_2 AVX
--       AVX2 (38 files):           + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2
--       AVX512_SKX (8 files):      + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX_512F AVX512_COMMON AVX512_SKX
--
--   C/C++:
--     Built as dynamic libs?:      YES
--     C++ standard:                11
--     C++ Compiler:                /usr/bin/c++  (ver 13.2.0)
--     C++ flags (Release):         -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG  -DNDEBUG
--     C++ flags (Debug):           -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -fvisibility-inlines-hidden -g  -O0 -DDEBUG -D_DEBUG
--     C Compiler:                  /usr/bin/cc
--     C flags (Release):           -fsigned-char -W -Wall -Wreturn-type -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -O3 -DNDEBUG  -DNDEBUG
--     C flags (Debug):             -fsigned-char -W -Wall -Wreturn-type -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -g  -O0 -DDEBUG -D_DEBUG
--     Linker flags (Release):      -Wl,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a   -Wl,--gc-sections -Wl,--as-needed -Wl,--no-undefined
--     Linker flags (Debug):        -Wl,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a   -Wl,--gc-sections -Wl,--as-needed -Wl,--no-undefined
--     ccache:                      YES
--     Precompiled headers:         NO
--     Extra dependencies:          dl m pthread rt
--     3rdparty dependencies:
--
--   OpenCV modules:
--     To be built:                 calib3d core dnn features2d flann gapi highgui imgcodecs imgproc ml objdetect photo python3 stitching ts video videoio
--     Disabled:                    world
--     Disabled by dependency:      -
--     Unavailable:                 java python2
--     Applications:                tests perf_tests apps
--     Documentation:               NO
--     Non-free algorithms:         NO
--
--   GUI:                           NONE
--     GTK+:                        NO
--     VTK support:                 NO
--
--   Media I/O:
--     ZLib:                        /usr/lib/x86_64-linux-gnu/libz.so (ver 1.2.13)
--     JPEG:                        libjpeg-turbo (ver 2.1.3-62)
--     WEBP:                        build (ver encoder: 0x020f)
--     PNG:                         build (ver 1.6.37)
--     TIFF:                        build (ver 42 - 4.2.0)
--     JPEG 2000:                   build (ver 2.5.0)
--     OpenEXR:                     build (ver 2.3.0)
--     HDR:                         YES
--     SUNRASTER:                   YES
--     PXM:                         YES
--     PFM:                         YES
--
--   Video I/O:
--     DC1394:                      NO
--     FFMPEG:                      NO
--       avcodec:                   NO
--       avformat:                  NO
--       avutil:                    NO
--       swscale:                   NO
--       avresample:                NO
--     GStreamer:                   NO
--     v4l/v4l2:                    YES (linux/videodev2.h)
--
--   Parallel framework:            pthreads
--
--   Trace:                         YES (with Intel ITT)
--
--   Other third-party libraries:
--     Intel IPP:                   2021.10.0 [2021.10.0]
--            at:                   /home/kmtr/work/build4-main_python3.12.0/3rdparty/ippicv/ippicv_lnx/icv
--     Intel IPP IW:                sources (2021.10.0)
--               at:                /home/kmtr/work/build4-main_python3.12.0/3rdparty/ippicv/ippicv_lnx/iw
--     VA:                          NO
--     Lapack:                      NO
--     Eigen:                       NO
--     Custom HAL:                  NO
--     Protobuf:                    build (3.19.1)
--     Flatbuffers:                 builtin/3rdparty (23.5.9)
--
--   OpenCL:                        YES (no extra features)
--     Include path:                /home/kmtr/work/opencv/3rdparty/include/opencl/1.2
--     Link libraries:              Dynamic load
--
--   Python 3:
--     Interpreter:                 /home/kmtr/.pyenv/shims/python3 (ver 3.12)
--     Libraries:                   /home/kmtr/.pyenv/versions/3.12.0/lib/libpython3.12.so (ver 3.12.0)
--     numpy:                       /home/kmtr/.pyenv/versions/3.12.0/lib/python3.12/site-packages/numpy/core/include (ver 1.26.1)
--     install path:                /home/kmtr/.pyenv/versions/3.12.0/lib/python3.12/site-packages/cv2/python-3.12
--
--   Python (for build):            /home/kmtr/.pyenv/shims/python3
--
--   Java:
--     ant:                         NO
--     Java:                        NO
--     JNI:                         NO
--     Java wrappers:               NO
--     Java tests:                  NO
--
--   Install to:                    /usr/local
-- -----------------------------------------------------------------
--
-- Configuring done (28.0s)
-- Generating done (0.2s)
-- Build files have been written to: /home/kmtr/work/build4-main_python3.12.0
cmake --build build4-main_python3.12.0
sudo cmake --install build4-main_python3.12.0
sudo ldconfig

これで、任意python versionで、OpenCV bindingが有効にできるようになりました!
試してみましょう!

kmtr@kmtr-None:~/work$ which python
/home/kmtr/.pyenv/shims/python
kmtr@kmtr-None:~/work$ python --version
Python 3.12.0
kmtr@kmtr-None:~/work$ python -c "import cv2 ; print(cv2.getVersionString())"
4.8.0-dev

それでは、楽しいOpenCV with Python lifeをお過ごしくださいませー!!

■ まとめ

  • 任意バージョンをインストールするのに、pyenvが便利です
  • OpenCVでpyenv使うには、ちょっと工夫(コマンドライン引数)が必要
  • これで古いlinuxでも最新python, opencvが活用できますね!
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?