Search code examples
pythonopencvpipenv

Opencv config with two major python (3.7 & 3.8)


For some time I was using opencv (4.5.2 compiled from source) with python 3.8.5 (on Ubuntu 18.04), but for some project, I do need to work with tensorflow, which is not working with my python version. So I installed python3.7 along it (from source), and everything seems to work when starting my pipenv shell, I can work with my python3.7.

But when trying to import cv2, I got the following error:

ImportError: OpenCV loader: missing configuration file: ['config-3.7.py', 'config-3.py']

So I believe I should re-compile OpenCV targeting my specific python3.7, but I also want to make it work with my former python3.8. How can I achieve this, targeting the two versions?

Thanks for you time!

Antoine


Solution

  • Well, in the end I succeeded in having the config files for both python3.7 and 3.8 with opencv built from source doing the following:

    I first compiled OpenCv without writing any parameters for pythons. So by default, it detected my Python3.8 and created the config-3.8.py file.

    Then, I recompiled OpenCv targeting my Python 3.7 with those arguments:

    cmake -DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib-master/modules ../opencv-master -D PYTHON3_EXECUTABLE='/usr/local/bin/python3.7m' \
    -D PYTHON_INCLUDE_DIR='/usr/local/include/python3.7m' \
    -D PYTHON3_LIBRARY='/home/ubuntu/Documents/Libraries/python3.7/Python-3.7.4/libpython3.7m.so' \
    -D PYTHON3_NUMPY_INCLUDE_DIRS='/usr/local/lib/python3.7/site-packages/numpy/core/include' \
    -D PYTHON3_PACKAGES_PATH='/usr/local/lib/python3.7/site-packages' ..
    

    Note that the PYTHON3_LIBRARY has to target the shared library(.so and not .a). I first compiled Python3.7 without the flag --enable-shared, so it was not working.

    Right before running cmake (from OpenCv), during the config step, you should end up with those printed information, to be sure you will target the right python: (Here it was for python3.8, but following the above steps will show python3.7)

    enter image description here

    Those PYTHON_FLAG and their usages are not in the latest Opencv documentation like the 4.5.2, but only in the previous ones like the 3.2.0:

    https://docs.opencv.org/4.5.2/d7/d9f/tutorial_linux_install.html

    https://docs.opencv.org/3.2.0/d7/d9f/tutorial_linux_install.html

    Then I was able to import cv2 both in 3.7 and 3.8