Created
January 3, 2021 12:04
-
-
Save bml1g12/e1e0af85e49bf46cccddbcf8e68a3708 to your computer and use it in GitHub Desktop.
Alternative to cv2.VideoCapture's set method for reliable frame seeking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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