OpenCV's VideoCapture is broken and hasn't been fixed for the last 5 years: opencv/opencv#9053
This is a PyAV based replacement. Unlike other implementations it can seek at any time.
How to use:
reader = VideoReader('video.mp4')
reader.seek(reader.total_frames - 100) # frame number
while True:
frame = reader.read()
if not frame:
break
# frame is an ndarray - do something with it
print(f'frame {reader.position}: {frame}')
reader.close()
@kwyoke it's possible that seeking will end up way too far off to the beginning of the file (e.g. due to a broken frame index), so the code bails out. 100 is an arbitrary number here.
A more robust way would be to carefully retry with a larger timestamp in the hope of then landing closer to the correct PTS.