1、 在有homebrew 的情况下,执行下面的安装指令
brew install opencv
安装成功后提示
Python modules have been installed and Homebrew's site-packages is not
in your Python sys.path, so you will not be able to import the modules
this formula installed. If you plan to develop with these modules,
please run:
mkdir -p /Users/ashimarzheng/Library/Python/2.7/lib/python/site-packages
echo 'import site; site.addsitedir("/usr/local/lib/python2.7/site-packages")' >> /Users/ashimarzheng/Library/Python/2.7/lib/python/site-packages/homebrew.pth
==> Summary
? /usr/local/Cellar/opencv/3.4.1_1: 563 files, 98.8MB
安装目录为 /usr/local/Cellar/opencv
2、 进入python 的site-packages 目录下制作替身:
文件目录根据opencv 的版本和Python版本灵活修改。
cd 到Python的site-packages中
ln -s 目标文件 文件名称
例如:
cd my_tf/lib/python3.5/site-packages
ln -s /usr/local/Cellar/opencv3/3.1.0_4/lib/python3.5/site-packages/cv2.cpython-35m-darwin.so cv2.so
这时候试试看是否成功
>>> import cv2
RuntimeError: module compiled against API version 0xc but this version of numpy is 0xb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: numpy.core.multiarray failed to import
接着下面的操作
3、安装相应的模块
pip install --upgrade setuptools
pip install numpy Matplotlib
pip install opencv-python
再试一次
$ python
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 12:01:12)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>>
哎呦,成功了!
拓展
对于多版本python, 则需要重复 第二步的操作,进入对应的python版本 制作替身,再进行第三步,pip 对应的版本。例如pip2 或pip3
安装了多版本python时(例如python2.6和2.7),pip安装的包不一定是用户想要的位置,此时可以用 -t 选项来指定位置.
例如目标位置是/usr/local/lib/python2.7/site-packages/ ,要安装xlrd 这个包,则:
pip install -t /usr/local/lib/python2.7/site-packages/ xlrd
登录 | 立即注册