在 Win10 或 win7 系统中用 python 3.7.6 执行 import cv2 的时候,往往提示找不到指定的模块。其实找不到的不是 cv2 这个模块,而是 opencv-python 模块。很多教程说 pip install opencv-python 之后,就可以 import cv2 成功。但是,事实证明在Windows系统中,这是解决不了问题的。
还有人说,先把 wheel 文件下载下来再安装就行了
(
下载地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv
)实践证明,也不可取。
所以,要解决的问题是在Windows7、10系统下import cv2失败。
我的Python版本:3.7.6
机缘巧合之下,我找到了这么一种方法,依次输入以下命令就可以了:
pip install --upgrade setuptools --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple/
这是更新 setuptools 的操作,其中 --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple/ 是设置信任主机和镜像服务器的操作,从域名上看,这是阿里云镜像服务器的地址。使用阿里云镜像服务器明显要比官方地址快的多。(以下其他命令也使用了同样的办法)
pip install numpy Matplotlib --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple/
这是安装 numpy 和 Matplotlib 库的操作。
pip install opencv-python --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple/
这是安装 opencv-python 库。
接下来我们安装 opencv-contrib-python 库(OpenCV将很多算法安装到了opencv-contrib内):
下面我们贴一段 Kivy 调用摄像头的代码:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
import time
Builder.load_string('''
<CameraClick>:
orientation: 'vertical'
Camera:
id: camera
resolution: (640, 480)
play: False
ToggleButton:
text: 'Play'
on_press: camera.play = not camera.play
size_hint_y: None
height: '48dp'
Button:
text: 'Capture'
size_hint_y: None
height: '48dp'
on_press: root.capture()
''')
class CameraClick(BoxLayout):
def capture(self):
'''
Function to capture the images and give them the names
according to their captured time and date.
'''
camera = self.ids['camera']
timestr = time.strftime("%Y%m%d_%H%M%S")
camera.export_to_png("IMG_{}.png".format(timestr))
print("Captured")
class Camera(App):
def build(self):
return CameraClick()
Camera().run()
运行结果如下:
如果 opencv-python 没有安装好,会报“找不到 camera 提供者”之类的错误。