Search code examples
opencvvideocameramp4video-processing

Why is the first frame of my video duplicated at the end, and being duplicated at the end of my frame extraction process using OpenCV?


I am extracting frames from a video using OpenCV. Once the process is finished and all frames are extracted, the code continues to extract the first frame of the video, seemingly infinitely.

This OpenCV code has worked for all of my videos so far except this one, which was shot with a different kind of camera, so I suspect something is different about the video file. Notably, when I play the video in Quick Time, the first frame of the video is shown at the end.

cap = cv2.VideoCapture('Our_Video.mp4')
i = 0
while(cap.isOpened()):
    
    cap.set(cv2.CAP_PROP_POS_FRAMES, i)
    
    IsNotEnd, frame = cap.read()
    if IsNotEnd == False:
        break
    
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imwrite(os.path.join('increment_'+str(i)+'.png'),gray)
    i+=1
    
cap.release()
cv2.destroyAllWindows()

Clearly, variable IsNotEnd is never being set to False – how can I change that setting from cap.read()? It clearly seems to relate to the first frame being shown after the video ends.


Solution

  • As suspected, the problem has to do with the end behavior of the video file itself. By changing the end behavior of the video file, then cap.read() correctly returns False at the final frame.