OpenCV and python/virtualenv?

Simply copy of the cv2*.so file to the site-packages folder of the virtual environment. For example:

cp /usr/lib/python3.6/dist-packages/cv2.cpython-36m-aarch64-linux-gnu.so ~/your_virt_env_folder/YOUR_VIRT_ENV_NAME/lib/python3.6/site-packages/

I use makefiles in my projects to install OpenCV inside Python virtualenv. Below is boilerplate example. It requires that you already have OpenCV bindings present for your system Python (/usr/bin/python) which you can get using something like yum install opencv-python or apt-get install python-opencv.

Make first queries system Python's cv2 module and retrieves location of installed library file. Then it copies cv2.so into the virtualenv directory.

VENV_LIB = venv/lib/python2.7
VENV_CV2 = $(VENV_LIB)/cv2.so

# Find cv2 library for the global Python installation.
GLOBAL_CV2 := $(shell /usr/bin/python -c 'import cv2, inspect; print(inspect.getfile(cv2))')

# Link global cv2 library file inside the virtual environment.
$(VENV_CV2): $(GLOBAL_CV2) venv
    cp $(GLOBAL_CV2) $@

venv: requirements.txt
    test -d venv || virtualenv venv
    . venv/bin/activate && pip install -r requirements.txt

test: $(VENV_CV2)
    . venv/bin/activate && python -c 'import cv2; print(cv2)'

clean:
    rm -rf venv

(You can copy-paste above snippet into a Makefile, but make sure to replace indentations with tab characters by running sed -i s:' ':'\t':g Makefile or similar.)

Now you can run the template:

echo "numpy==1.9.1" > requirements.txt
make
make test

Note that instead of symbolic link, we actually copy the .so file in order to avoid problem noted here: https://stackoverflow.com/a/19138136/1510289


Virtualenv creates a separate python environment. You will need to re-install all of your dependencies. EDIT it's true pip does not seem to play well with opencv. The missing module error can be resolved by copying cv shared object to your virtualenv. More info in the question linked below.