【问题标题】:TypeError: 'NoneType' and cv2.error in PythonTypeError:Python 中的“NoneType”和 cv2.error
【发布时间】:2018-11-20 12:18:27
【问题描述】:

在回答我的问题之前,我知道这是一个非常常见的问题,但取决于代码,可能有多种解决方案,所以如果有人能帮助我,我将非常感激。

总的来说,我对 Python 和 ML 非常陌生。所以在运行我的 create_gesture.py 文件时,我得到了 NoneType 错误。 我的代码:

create_folder("gestures/" + str(g_id))
pic_no = 0
flag_start_capturing = False
frames = 0

while True:
    img = cam.read()[1]
    img = cv2.flip(img, 1)
    imgCrop = img[y:y + h, x:x + w]
    imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    dst = cv2.calcBackProject([imgHSV], [0, 1], hist, [0, 180, 0, 256], 1)
    disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))
    cv2.filter2D(dst, -1, disc, dst)
    blur = cv2.GaussianBlur(dst, (11, 11), 0)
    blur = cv2.medianBlur(blur, 15)
    thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    thresh = cv2.merge((thresh, thresh, thresh))
    thresh = cv2.cvtColor(thresh, cv2.COLOR_BGR2GRAY)
    thresh = thresh[y:y + h, x:x + w]
    contours = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]

我收到此错误:

Traceback (most recent call last):
  File "create_gestures.py", line 120, in <module>
    store_images(g_id)
  File "create_gestures.py", line 70, in store_images
    imgCrop = img[y:y + h, x:x + w]
TypeError: 'NoneType' object is not subscriptable

编辑

找出行中的整数值

img = cam.read()[1]    

抛出错误。应该是 0 而不是 1。但现在我得到一个不同的错误:

Traceback (most recent call last):
File "create_gestures.py", line 121, in <module>
store_images(g_id)
File "create_gestures.py", line 72, in store_images
imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
cv2.error: OpenCV(3.4.1) D:\Build\OpenCV\opencv 3.4.1\modules\imgproc\src\color.cpp:11109: error: (-215) depth == 0 || depth == 2 || depth == 5 in function cv::cvtColor

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    NoneType 意味着您实际上拥有的不是您认为正在使用的任何类或对象的实例。这通常意味着上面的赋值或函数调用失败或返回了意外的结果。

    【讨论】:

    • 是的,我从这里的其他类似问题中得到了这一点,但问题是我似乎无法在我的代码中找到函数调用完全失败的位置。
    【解决方案2】:

    在这行代码之后检查变量img 中的内容:img = cam.read()[1]。你的cam.read()[1] 可能返回None,你应该在继续之前检查那行代码是否正常工作。

    【讨论】:

    • 是的,它确实没有返回任何内容。我认为索引号错误,所以我将其更改为img = cam.read()[0],我现在收到此错误:cv2.error: OpenCV(3.4.1) D:\Build\OpenCV\opencv-3.4.1\ modules\imgproc\src\color.cpp:11109: 错误:(-215) depth == 0 ||深度 == 2 ||函数 cv::cvtColor 中的深度 == 5
    • @ShibeshDuwadi 我没有使用 cv2 库的经验,但也许这可以帮助你:stackoverflow.com/questions/30506126/…
    猜你喜欢
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多