在此脚本中: -
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
我收到此错误: -
我做错了什么。我甚至在全球范围内定义了相机,即TWICE。可以somone请在代码中指出我的错误?我使用带有Opencv模块的python 2.7
File "C:\Python27\Scripts\Servers.py", line 22, in Camera
temp = get_image()
File "C:\Python27\Scripts\Servers.py", line 16, in get_image
retval, im = camera.read()
NameError: global name 'camera' is not defined
更新 请查看上面的更新代码
答案 0 :(得分:5)
您还需要在方法范围之外定义camera
。 global
关键字的作用是告诉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