python中未定义全局名称“camera”

2024-06-16 15:04:30 发布

您现在位置:Python中文网/ 问答频道 /正文

在本脚本中:

camera_port = 0
ramp_frames = 400
camera = cv2.VideoCapture(camera_port) 
def get_image():
  global camera
  retval, im = camera.read()
  return im

def Camera():
    global camera
    for i in xrange(ramp_frames):
     temp = get_image()
    print("Taking image...")
    camera_capture = get_image()
    file = "opencv.png"
    cv2.imwrite(file, camera_capture)
    del(camera)

def Sendmail():
    loop_value = 1
    while loop_value==1:
        try:
            urllib2.urlopen("https://google.com")
        except urllib2.URLError, e:
            print "Network currently down." 
            sleep(20)
        else:
            print "Up and running." 
            loop_value = 0
def Email():
    loop_value = 2
    while loop_value==2:
        try:
            Camera()
            Sendmail()
            yag = yagmail.SMTP('email',   'pass')
            yag.send('amitaagarwal565@gmail.com', subject = "This is    opencv.png", contents = 'opencv.png')
            print "done"
        except smtplib.SMTPAuthenticationError:
            print 'Retrying in 30 seconds'
            sleep(30)
        else:
            print 'Sent!'
            sleep(20)
            loop_value = 2

我得到这个错误:

我做错什么了。我甚至在全球范围内定义了摄像头,将其定义为两次。有人能指出我在密码里的错误吗?我在Opencv模块中使用python2.7

^{pr2}$

更新 查看上面更新的代码


Tags: imageloopgetframespngvalueportdef
1条回答
网友
1楼 · 发布于 2024-06-16 15:04:30

您还需要在方法的范围之外定义cameraglobal关键字的作用是告诉Python您将修改您在外部定义的变量。如果你没有,你会得到这个 错误。在

编辑

我没有注意到您已经对外声明了camera。但是,您可以删除Camera()方法中的变量,当您再次尝试修改该变量时,它的效果几乎相同。在

编辑2

现在我可以看到您的代码真正做什么以及您打算做什么,我认为您根本不应该使用全局camera,而是将其作为参数传递。这应该是有效的:

camera_port = 0
ramp_frames = 400

def get_image(camera):
    retval, im = camera.read()
    return im

def Camera(camera):
    for i in xrange(ramp_frames):
        temp = get_image(camera)
    print("Taking image...")
    camera_capture = get_image(camera)
    file = "opencv.png"
    cv2.imwrite(file, camera_capture)

def Sendmail():
    loop_value = 1
    while loop_value==1:
        try:
            urllib2.urlopen("https://google.com")
        except urllib2.URLError, e:
            print "Network currently down." 
            sleep(20)
        else:
            print "Up and running." 
            loop_value = 0

def Email():
    loop_value = 2
    while loop_value==2:
        try:
            camera = cv2.VideoCapture(camera_port) 
            Camera(camera)
            Sendmail()
            yag = yagmail.SMTP('email',   'pass')
            yag.send('amitaagarwal565@gmail.com', subject = "This is    opencv.png", contents = 'opencv.png')
            print "done"
        except smtplib.SMTPAuthenticationError:
            print 'Retrying in 30 seconds'
            sleep(30)
        else:
            print 'Sent!'
            sleep(20)
            loop_value = 2

相关问题 更多 >