0

I'm running a code on deep learning, which uses the opencv module, by running python main.py (contains import cv2 statement), but always get the error 'ImportError: dynamic module does not define module export function (PyInit_cv2)'.

I've tried to reinstall my anaconda and create new virtual environments, but all got the same result. This problem really confuses me a lot and I've googled for many related problems, none of them works. I think the problem is something related to the environment and has nothing to do with the code, because I got the same result by simply run import cv2 in python prompt. The more confusing thing is that, even after I remove the opencv module, I also get the same problem, but not a ModuleNotFoundError. Does anyone can give me some advice? Thanks a lot!

3 Answers3

2

I think I found one possible reason of this error. Recently I was configuring the caffe environment on one server, I downloaded the source code of opencv-2.4.13 and compiled manually, added /usr/local/opencv-2.4.13/build/lib to $PYTHONPATH, and caffe worked well. After that, when I entered one of my virtual environment using conda activate py35, which uses python3.5, tried import cv2 in the python prompt, got the error above.

I'm not sure but I think the cause of the error is opencv-2.4.13 compiles a python2 interface so it can't be imported by python3. Python imports packages by searching the directories listed in sys.path, where $PYTHONPATH is in the second place after the current working directory (This is a great article introduces the mechanism of python finding packages). So when we enter the py35 environment, python will first look for $PYTHONPATH and find the opencv installed on the root directory instead of finding the opencv in the virtual environment using conda install opencv-python.

So there are two solutions of this problem:

  1. Use python2 instead.
  2. Remove /usr/local/opencv-2.4.13/build/lib from $PYTHONPATH.

which all work for me.

0

Similar post, might help: ImportError: dynamic module does not define init function (initfizzbuzz)

Could you provide info on how you installed the CV module?

Julio P.C.
  • 321
  • 1
  • 7
  • I've read that post before, but it seems doesn't work for me. I've tried `conda install opencv` and `pip install opencv-python`, but all return the same error. – NarcissusInMirror Dec 26 '18 at 04:05
0

I had the same problem, which was caused by the cv2.so file in /usr/local/lib/python2.7/site-packages/cv2.so. After I deleted the file and use command sudo pip3 install opencv-python, it worked for python3.

Cwang
  • 371
  • 3
  • 9