Home > OS >  How do i solve this TypeError: 'NoneType' object is not subscriptable?
How do i solve this TypeError: 'NoneType' object is not subscriptable?

Time:05-01

cap = cv2.VideoCapture(0)
while 1:
    ret,img = cap.read()
    image = cv2.imread('/content/drive/MyDrive/signProject/amer_sign2.png')
    cv2_imshow(image)
    img = cv2.flip(img, 1)
    top, right, bottom, left = 75, 350, 300, 590
    roi = img[top:bottom, right:left]
    roi=cv2.flip(roi,1)
    gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (7, 7), 0)
    cv2_imshow(gray)
    alpha=classify(gray)
    cv2.rectangle(img, (left, top), (right, bottom), (0,255,0), 2)
    font=cv2.FONT_HERSHEY_SIMPLEX
    cv2.putText(img,alpha,(0,130),font,5,(0,0,255),2)
    #cv2.resize(img,(1000,1000))
    cv2_imshow(img)
    key = cv2.waitKey(1) & 0xFF
    if key==ord('q'):
        break;
cap.release()
cv2.destroyAllWindows()
--------------------------------------------------------------------------- 
TypeError                                 Traceback (most recent call last) <ipython-input-36-105ee52e9f68> in <module>()
      6     img = cv2.flip(img, 1)
      7     top, right, bottom, left = 75, 350, 300, 590
----> 8     roi = img[top:bottom, right:left]
      9     roi=cv2.flip(roi,1)
     10     gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)

TypeError: 'NoneType' object is not subscriptable

code

error

CodePudding user response:

The error message means that, for some reason, img is equal to None, so roi = img[top:bottom, right:left] triggers the error.

CodePudding user response:

The error means you are trying to index an object which can't be indexed (in this case a NoneType). So img in line 8 seems to be None. This is probably due to ret, img = cap.read() failing. The first return value in cap.read() (in your case called ret) indicates whether or not cap.read() was sucessful. You should check if ret is True before using img.

  • Related