简体   繁体   中英

How to link openCv with Python3 in mac Os

I have two versions of python in my mac os, the first python2.7 which is the default that came with the system. Later I installed python3.7 that I use most of the time.

I have recently installed openCV using homebrew. When I'm using openCV with python2.7, it's working normally.

But the problem is when I try to use it with python3. Importing cv2 in python3 gives error: ModuleNotFoundError: No module named 'cv2'

Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 03:03:55) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable.
Visit http://www.python.org/download/mac/tcltk/ for current 
information.

>>> import cv2
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
import cv2
ModuleNotFoundError: No module named 'cv2'
>>> 

Is there anything I can do so that I can link the installed openCV with python3 ??

Thanks for the help

Sorry I cannot give you specifics because your setup is not identical to mine, but I am sure we can get you sorted out.

Firstly, when you install packages, such as OpenCV , they tend to create a directory somewhere called lib which contains the C/C++ functions you can call from that package. Inside that directory, you normally find "shared object libraries" which traditionally end in "XXX.so" on macOS. More interestingly, they also contain a sub-directory called site-packages which contains the Python bindings (links). So, on my system, which is likely different from yours, I can find all those site-packages directories with:

find / -type d -name site-packages 2>/dev/null

Sample Output

/usr/local/lib/python3.7/site-packages
/usr/local/lib/python2.7/site-packages
...
...
/usr/local/Cellar/tbb/2018_U5/lib/python2.7/site-packages
/usr/local/Cellar/vips/8.6.5/lib/python3.7/site-packages

Hopefully, you can see that /usr/local/lib/python3.7/site-packages is looking a very likely candidate for where all the Python v3.7 bindings for OpenCV should be.

Good, so now we know how to find the Python bindings, we need to tell Python that information. How? Well, not unreasonably, Python looks at an environment variable called PYTHONPATH to find its stuff. So, using our skill and judgement we need to marry up what we found in the first step with what we now know from the second step. So we do:

export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python3.7/site-packages

And everything should work. All we need to do is put that in our login profile (probably $HOME/.profile ) and we will be ready to go every time we log in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM