Skip to content

Instantly share code, notes, and snippets.

@benJephunneh
Last active January 19, 2019 23:29
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 benJephunneh/4cf9eb0b20e82dfe979a2fa15874d0e3 to your computer and use it in GitHub Desktop.
Save benJephunneh/4cf9eb0b20e82dfe979a2fa15874d0e3 to your computer and use it in GitHub Desktop.
Extract nth frames from video file using Python 3.6.1 and OpenCV
import os
import errno
import cv2
def extractFrames(videoFile, pathOut):
# Create output directory:
try:
os.mkdir(pathOut)
except OSError as exc:
if exc.errno is not errno.EEXIST:
raise
pass
# Open video file, create nth-frame counter at first frame (0), set video read to that frame, and read frame:
cap = cv2.VideoCapture(videoFile)
count = 0
cap.set(1, count)
ret, frame = cap.read()
# Loop nth-frame counter until end of video file:
while ret:
# Console output for debugging:
print('Read %d frame: ' % count, ret)
# Write nth frame to file (frame_N_.jpg)
cv2.imwrite(os.path.join(pathOut, "frame{:d}.jpg".format(count)), frame)
# Set capture interval. E.g. with a video at 30fps, count += 30 captures frames at 1-second intervals
count += 30
cap.set(1, count)
ret, frame = cap.read()
# End of loop; close video file; close image windows (which I didn't open, here):
cap.release()
cv2.destroyAllWindows()
def main():
# Call frame-extraction method with filename and directory parameters:
extractFrames('hw2.1.avi',
'Macro_temp')
if __name__=='__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment