I am trying to build a Docker container that can run Python OpenCV code in Raspbian 10.

FROM python:3.5-buster
RUN apt-get update
RUN apt-get install apt-utils -y
RUN apt-get install python-opencv -y
RUN apt-get install python3-opencv -y
COPY a.py /
CMD ["python3", "a.py"]

a.py is simply import cv2

When I run the container, I got the following errors.

Traceback (most recent call last):
  File "a.py", line 1, in <module>
    import cv2
ImportError: No module named 'cv2'

Three workarounds:

  • Use debian:buster as your base container instead of python:3.5-buster


  • Put this into your Dockerfile:
ENV PYTHONPATH /usr/lib/python3/dist-packages


  • Similarly, put this at the top of a.py:
import sys

import cv2

It's unclear why Python's package path system is so fragile, but the last two are a variation of suggestions on a similar question[1], and among the quickest workarounds I could verify.

[1] Cannot find module cv2 when using OpenCV

  • Thank you very much. The 1st method works. But not the 2nd method.
    – wannik
    Aug 11 '19 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.