The global name "camera" is not defined in python

In this script: -

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 

I get this error: -

What am I doing wrong. I even spotted a camera around the world that TWICE. Can someone point out my error in the code? I am using python 2.7 with opencv module

 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 

UPDATE Look above for updated code

+6
source share
1 answer

You must define camera outside the scope of your methods. What the global keyword does is tell Python that you will change this variable that you defined externally. If you have not done so, you will receive this error.

EDIT

I didn’t notice that you already declared camera from the outside. However, you delete the variable inside the Camera() method, which has almost the same effect when you try to change this variable again.

EDIT 2

Now that I see what your code really does and what you intend to do, I don’t think you should work with the global camera , but pass it as a parameter. This should work:

 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 
+5
source

All Articles