解决anaconda中已经安装了opencv3,但无法import的问题
你可能遇见的问题:
- ImportError: No module named cv2
- ImportError: libz-a147dcb0.so.1.2.3: cannot open shared object file: No such file or directory
第一个问题:
你可能没有成功安装opencv环境,或者你需要重新安装opencv的环境进行尝试
你可以查看这一篇博客进行配置opencv卸载与安装
第二个问题:
你可能查看了某些博客,要求你将cv2.so移动到你的使用的python中( sudo cp /usr/local/lib/python2.7/dist-packages/cv2/cv2.so /home/username/anaconda3/lib/python3.6/dist-packages/),然后你再次import cv2
就会发现会出现以上的报错
你可以通过which python
命令查看你的python的来源。例如你通过which python
得到的结果是/home/learner/anaconda3/bin/python
那么说明你需要的opencv文件应该放在anaconda3/lib/python3.6(你的对应的版本)/dist-packages/中
解决方法:
如果你确实已经按照以上的博客进行安装好opencv了,那么你可以继续进行,否则,请先按照以上博客进行opencv的安装。
根据提示,缺少的是libz-a147dcb0.so.1.2.3这个文件,那么我们进行查找通过sudo find / -name libz-a147dcb0.so.1.2.3
得到结果如下:
find: ‘/run/user/1000/gvfs’: Permission denied
/var/lib/docker/overlay2/f72d8ff7ad2486a45a06a7bccdebe2628377a839c7f943d7e2b06f44a825be87/diff/usr/local/lib/python3.6/dist-packages/PIL/.libs/libz-a147dcb0.so.1.2.3
/var/lib/docker/overlay2/f72d8ff7ad2486a45a06a7bccdebe2628377a839c7f943d7e2b06f44a825be87/diff/usr/local/lib/python3.6/dist-packages/h5py/.libs/libz-a147dcb0.so.1.2.3
/var/lib/docker/overlay2/f72d8ff7ad2486a45a06a7bccdebe2628377a839c7f943d7e2b06f44a825be87/diff/usr/local/lib/python3.6/dist-packages/matplotlib/.libs/libz-a147dcb0.so.1.2.3
/home/learner/.conda/envs/tensorflow/lib/python3.6/site-packages/PIL/.libs/libz-a147dcb0.so.1.2.3
/home/learner/.conda/envs/tensorflow/lib/python3.6/site-packages/h5py/.libs/libz-a147dcb0.so.1.2.3
/home/learner/.conda/envs/tensorflow/lib/python3.6/site-packages/matplotlib/.libs/libz-a147dcb0.so.1.2.3
/home/learner/.conda/envs/tensorflow/lib/python3.6/site-packages/cv2/.libs/libz-a147dcb0.so.1.2.3
/home/learner/.conda/envs/tf/lib/python3.6/site-packages/PIL/.libs/libz-a147dcb0.so.1.2.3
/home/learner/.conda/envs/tf/lib/python3.6/site-packages/h5py/.libs/libz-a147dcb0.so.1.2.3
/home/learner/.conda/envs/tf/lib/python3.6/site-packages/matplotlib/.libs/libz-a147dcb0.so.1.2.3
/home/learner/.conda/envs/tf/lib/python3.6/site-packages/cv2/.libs/libz-a147dcb0.so.1.2.3
/usr/local/lib/python3.5/dist-packages/cv2/.libs/libz-a147dcb0.so.1.2.3
/usr/local/lib/python3.5/dist-packages/matplotlib/.libs/libz-a147dcb0.so.1.2.3
/usr/local/lib/python2.7/dist-packages/h5py/.libs/libz-a147dcb0.so.1.2.3
/usr/local/lib/python2.7/dist-packages/cv2/.libs/libz-a147dcb0.so.1.2.3
/usr/local/lib/python2.7/dist-packages/matplotlib/.libs/libz-a147dcb0.so.1.2.3
我们可以观察到有很多cv2的文件夹,而我们python所使用的anaconda3/lib/python3.6/site-packages中没有这个文件,那么将cv2.so文件复制过去
cp /usr/local/lib/python2.7/dist-packages/cv2.so /anaconda3/lib/python3.6/site-packages
在此处还不够,需要加上以下声明,可以添加到.bashrc中
export PYTHONPATH=/home/learner/anaconda3/lib/python3.6/site-packages/:$PYTHONPATH
验证结果
Python 3.6.3 |Anaconda, Inc.| (default, Oct 13 2017, 12:02:49)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>>
这个方法是我误打误撞得到的,如果有更好的方法,希望大家可以给我留言,我会继续改进的