Skip to content

Instantly share code, notes, and snippets.

@bml1g12
Created January 3, 2021 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bml1g12/e1e0af85e49bf46cccddbcf8e68a3708 to your computer and use it in GitHub Desktop.
Save bml1g12/e1e0af85e49bf46cccddbcf8e68a3708 to your computer and use it in GitHub Desktop.
Alternative to cv2.VideoCapture's set method for reliable frame seeking
def seekTo(cap, position):
'''
Work around bug in OpenCV set method: https://github.com/opencv/opencv/issues/9053
The alternative routine to seek in the video file, a bit slow.
Required because FFMPEG can seek only to closest I-frames and we
have to manually read all the P-frames until we reach the position
'''
positiontoset = position
pos = -1
cap.set(cv2.CAP_PROP_POS_FRAMES, position)
while pos < position:
ret, image = cap.read()
pos = cap.get(cv2.CAP_PROP_POS_FRAMES)
if pos == position:
return image
elif pos > position:
positiontoset -= 1
cap.set(cv2.CAP_PROP_POS_FRAMES, positiontoset)
pos = -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment