NameError: name 'VideoCapture' is not defined

NameError: name 'VideoCapture' is not defined

过去几天我尝试使用 OpenCV 将图像保存到指定文件夹,但我经常发现此错误:

Traceback (most recent call last):
  File "C:\Users\himik\Desktop\[REDACTED]\[REDACTED]\IMGTEST.py", line 3, in <module>
    cam = VideoCapture(0)   # 0 -> index of camera
NameError: name 'VideoCapture' is not defined

我的代码如下:

from cv2 import *

cam = VideoCapture(0)   
s, img = cam.read()
if s:
    namedWindow("cam-test",CV_WINDOW_AUTOSIZE)
    imshow("cam-test",img)
    waitKey(0)
    destroyWindow("cam-test")
    imwrite("filename.jpg",img)

关于如何解决我的问题有什么建议或想法吗? 编辑:删除了不相关的信息!

基本上问题出在您的 from cv2 import * 上。我只是将您指向互联网,了解您为什么不应该我们 import *
铁。 this medium article 有一个很好的 write-up。请务必也点击该文章中的链接。

有两个简单的修复程序可用。首先,将 cv2 导入其适当的命名空间。

import cv2 as cv

cam = cv.VideoCapture(0)   
s, img = cam.read()
if s:
    cv.namedWindow("cam-test")
    cv.imshow("cam-test",img)
    cv.waitKey(0)
    cv.destroyWindow("cam-test")
    cv.imwrite("filename.jpg",img)

选项2,从cv2导入特定部分。请注意,我强烈建议您在此处使用选项 1。

from cv2 import (VideoCapture, namedWindow, imshow, waitKey, destroyWindow, imwrite)

cam = VideoCapture(0)   
s, img = cam.read()
if s:
    namedWindow("cam-test")
    imshow("cam-test",img)
    waitKey(0)
    destroyWindow("cam-test")
    imwrite("filename.jpg",img)