Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

Raspberry Pi 3B+ とPython3な環境に OpenCV環境をつくる

みんな大好きOpenCV
今回は、OpenCVを Python3 on RasPi3B+ な環境に突っ込んでみます。
(ただし、諸事情によりOpenCVは最新版でなく3.4系を入れます)

実際のところ

sudo apt update
sudo apt autoremove
sudo apt upgrade -y
sudo reboot
$ sudo apt-get install libhdf5-dev libhdf5-serial-dev libhdf5-dev
$ sudo apt-get install libqtgui4 libqtwebkit4 libqt4-test python3-pyqt5
$ sudo apt-get install libatlas-base-dev
$ sudo apt-get install libjasper-dev
$ sudo apt-get install python3-opencv

*1

opencv は諸事情により3系の最新版を導入。
執筆時点では4.1系があるので、マトモな事情の人は最新版をいれませう

$ pip3 install opencv-contrib-python==3.4.7.28

試しに読み込めてるか確認。

$ python3 
Python 3.7.3 (default, Dec 20 2019, 18:57:59) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv.__version__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'cv' is not defined
>>> cv2.__version__
'3.4.7'

ビルド??

opencv-contrib-python · PyPI
によると

Q: Pip fails with Could not find a version that satisfies the requirement ...?

A: Most likely the issue is related to too old pip and can be fixed by running pip install --upgrade pip. Note that the wheel (especially manylinux) format does not currently support properly ARM architecture so there are no packages for ARM based platforms in PyPI. However, opencv-python packages for Raspberry Pi can be found from https://www.piwheels.org/.

とあり、ARMの実装はPC用より対応バージョンが遅れることがある模様。

$ pip3 install opencv-contrib-python==3.4.9.31
WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.
To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.
Defaulting to user installation because normal site-packages is not writeable
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
ERROR: Could not find a version that satisfies the requirement opencv-contrib-python==3.4.9.31 (from versions: 3.4.2.16, 3.4.2.17, 3.4.3.18, 3.4.4.19, 3.4.6.27, 3.4.7.28, 4.0.1.24, 4.1.0.25, 4.1.1.26)
ERROR: No matching distribution found for opencv-contrib-python==3.4.9.31

*1:libhdf5-100とか書いてあるところがありますが、多分態々バージョン指定しなくともdev突っ込んだ方が無難です