【问题标题】:NameError: name 'cap' is not defined [duplicate]NameError:名称'cap'未定义[重复]
【发布时间】:2020-02-20 14:19:46
【问题描述】:

我在

中定义了cap
def fingerCursor(device):
    global cap
    global cap_height
    global cap_width
    cap = cv2.VideoCapture(device)
        #cap.set(cv2.cap_PROP_FRAME_HEIGHT,720)
        #cap.set(cv2.cap_PROP_FRAME_WIDTH,1280)
    cap_height = cap.get(cv2.cap_PROP_FRAME_HEIGHT)
    cap_width = cap.get(cv2.cap_PROP_FRAME_WIDTH)
        #print(cap_height,cap_width)

但每当我运行这部分代码时,它仍然显示 cap 未定义。 cap_heightcap_width 也有同样的问题。

while(cap.isOpened()):
        ## capture frame-by-frame
        ret, frame_raw = cap.read()
        while not ret:
            ret,frame_raw = cap.read()
        frame_raw = cv2.flip(frame_raw, 1)
        frame = frame_raw[:round(cap_height),:round(cap_width)] # ROI of the image
        cv2.imshow("raw_frame",frame)

【问题讨论】:

    标签: python machine-learning deep-learning computer-vision artificial-intelligence


    【解决方案1】:

    您的变量必须在您的函数之外定义。而且你必须保持你的行以global 开头,以声明你想在你的函数之外修改这些变量。

    【讨论】:

      【解决方案2】:

      您不会在全局范围内创建变量。无论如何,以这种方式使用global 通常是个坏主意。我建议将您的功能更改为:

      def fingerCursor(device):
          cap = cv2.VideoCapture(device)
          cap_height = cap.get(cv2.cap_PROP_FRAME_HEIGHT)
          cap_width = cap.get(cv2.cap_PROP_FRAME_WIDTH)
          return (cap, cap_height, cap_width)
      

      然后像这样使用它:

      cap, cap_height, cap_width = fingerCursor(whatever)
      

      【讨论】:

      • 嘿,感谢您的帮助,我尝试用您的代码更改我的代码,但现在生成了一个新错误
      • AttributeError: 模块 'cv2' 没有属性 'cap_PROP_FRAME_HEIGHT'
      猜你喜欢
      • 2018-08-01
      • 2020-06-17
      • 2016-07-06
      • 2015-10-22
      • 2016-05-12
      • 2011-11-19
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      相关资源
      最近更新 更多