Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

to loop through a video, but I've found that it always errors out on the last frame. I'm currently using this instead

while (cap.get(1) < cap.get(7)):

but is there something I need to do to get the first method to work and not error out?

I'm just doing normal things within the while loop; an example is below:

while (cap.get(1) < cap.get(7)): #(cap.isOpened()):
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'): 
        break

The first method is most likely failing because you're reading a frame after the video is over (and thus getting a blank frame), and then trying to do things to that blank frame which aren't allowed. You can add a check to see if the frame you got was blank:

    while(cap.isOpened()):
        ret, frame = cap.read()
        if frame is None:
            break

I believe this should fix the issue.

# reading frames success, img = cap.read() # success will be true if the images are read successfully. if success: # Do your work here else: print("Did not read the frame") What does this answer add to the answer that has already been accepted? If there is a valuable addition, please explain it. Otherwise, please delete it. – Captain Hat Dec 9, 2022 at 13:12

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.