Home > Software design >  frame is NoneType after a few seconds of video openCV
frame is NoneType after a few seconds of video openCV

Time:03-08

When executing

cap = cv2.VideoCapture("vid.mp4")

while True:
    ret, frame = cap.read()
    
    (height, width) = frame.shape[:2]  ###
    print(height)
    minimap = frame[1648:1920, 800:1080]

    if cv2.waitKey(1) == 27:
        exit(0)

I can see that for a few seconds, frame has a height and width but it suddently crashes due to the fact that "'NoneType' object has no attribute 'shape'" (on line with the ###). Any idea why ?

CodePudding user response:

You need to mainly check whether the frame is valid or not for the code.

cap = cv2.VideoCapture("vid.mp4")

while True:
    ret, frame = cap.read()
    if frame is not None:  # add this line
        (height, width) = frame.shape[:2] 
        print(height)
        minimap = frame[1648:1920, 800:1080]

    if cv2.waitKey(1) == 27:
        exit(0)

Also, for capturing the video frames, there is official documentation in OpenCV that might ease debugging your code.

https://docs.opencv.org/4.x/dd/d43/tutorial_py_video_display.html

CodePudding user response:

Generally, we receive empty/invalid frames when we reach the end of the video. You can check it once, and also print the frames. A similar question is posted here.

  • Related