Skip to content
Advertisement

NameError: name ‘VideoCapture’ is not defined [closed]

I’ve tried to save an image using OpenCV to a specified folder in the past days however i constantly find this error:

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

My code is below:

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)

Any suggestions or ideas on how to solve my issue? Edit: removed irrelevant information!

Advertisement

Answer

Basically the issue is with your from cv2 import *. I’ll just point you to the internet as to why you shouldn’t us import *.
FE. this medium article has a nice write-up. Be sure to follow the links in that article as well.

There are two easy fixes available. First, import cv2 into its proper namespace.

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)

Option 2, import specific parts from cv2. Note that I would very strongly advise to use option 1 here.

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)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement