NameError:未定义全局名称“initialZ”

时间:2014-07-05 18:57:15

标签: python opencv numpy

显示错误

Traceback (most recent call last):
  File "C:\Python27\sample\sample1.py", line 119, in <module>
    Position(np.array(list(threshold)))
  File "C:\Python27\sample\sample1.py", line 57, in Position
    print " Z = " ; print initialZ
NameError: global name 'initialZ' is not defined

代码

import cv2
import numpy as np
H_MIN = 0;
H_MAX = 256;
S_MIN = 0;
S_MAX = 256;
V_MIN = 0;
V_MAX = 256;
lastX = -1
lastY = -1

def nothing(x):
    pass

def morphOps(thresh):

    #create structuring element that will be used to "dilate" and "erode" image.
    #the element chosen here is a 3px by 3px rectangle

    erodeElement = cv2.getStructuringElement( cv2.MORPH_RECT, (3,3));
    #dilate with larger element so make sure object is nicely visible
    dilateElement = cv2.getStructuringElement( cv2.MORPH_RECT,(8,8));

    cv2.erode(thresh,thresh,erodeElement);
    cv2.erode(thresh,thresh,erodeElement);

    cv2.dilate(thresh,thresh,dilateElement);
    cv2.dilate(thresh,thresh,dilateElement);

i = 0

def initialValue(z):
     global i

     if i == 0:
         initialZ = z
         i = i + 1
         return initialZ

def Position(thresh):
    #moments are used to identify the shapes of the tracked image
       mu = cv2.moments(thresh,True);
       mx = mu['m10']
       my = mu['m01']
       area = mu['m00']

       if(area>100):
         X = mx/area;
         Y = my/area;
         Z = area;

         initialValue(Z)
         print " Z = " ; print initialZ

         if lastX>=0 & lastY>=0 & X>=0 & Y>=0 :
             print X ,Y, Z
             dX = X - 325;
             dY = 233 - Y;
             dZ = Z - initialZ;
             print " dX = "; print dX 
             print " dY = "; print dY
             print " dZ = "; print dZ

         lastX=X;
         lastY=Y;

videoCapture = cv2.VideoCapture('E:\Intern MNIT(gait motions)\Sample video.mp4')
fps = videoCapture.get(cv2.cv.CV_CAP_PROP_FPS)
print 'Frame per seconds : '; print fps

while 1 :
    frame,cameraFeed = videoCapture.read()
    HSV = cv2.cvtColor(cameraFeed,cv2.COLOR_BGR2HSV);
    #cv2.imshow('ORIGINAL' ,cameraFeed)
    #cv2.imshow('HSV' ,HSV)
    # define range of color in HSV
    lower = np.array([0,0,0])
    upper = np.array([256,256,256])

    #thresholding image
    threshold = cv2.inRange(HSV,lower,upper)

    #call morphOps function
    morphOps(np.array(list(threshold)))

    #cv2.imshow('Threshold Image' ,threshold)

    #call Position Function
    Position(np.array(list(threshold)))

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break


videoCapture.release()    
cv2.destroyAllWindows()

2 个答案:

答案 0 :(得分:1)

替换

  initialValue(Z)
  print " Z = " ; print initialZ

  initialZ = initialValue(Z)
  print " Z = " ; print initialZ

答案 1 :(得分:0)

这是在Python中定义全局变量的方法。

#!/usr/bin/env python

def main():
  compute_something()
  global i_am_global
  #use this variable anywhere now.
if __name__ =  "__main__"
 main()