Skip to content

Instantly share code, notes, and snippets.

@arundasan91
Created April 14, 2017 19:56
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 arundasan91/25275b06d1a05f9f6ee34e572b58f756 to your computer and use it in GitHub Desktop.
Save arundasan91/25275b06d1a05f9f6ee34e572b58f756 to your computer and use it in GitHub Desktop.
Function to extract frames from input video file using OpenCV and save them as separate frames in an output directory.
def video_to_frames(input_loc, output_loc):
"""Function to extract frames from input video file and save them as separate frames in an output directory.
Args:
input_loc: Input video file.
output_loc: Output directory to save the frames.
Returns:
None
"""
import time
import cv2
import os
try:
os.mkdir(output_loc)
except OSError:
pass
time_start = time.time()
cap = cv2.VideoCapture(input_loc)
video_length = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)) - 1
print "Number of frames: ", video_length
count = 0
print ("Converting video..\n")
while cap.isOpened():
ret,frame = cap.read()
cv2.imwrite(output_loc + "/%#05d.jpg" % (count+1), frame)
count = count + 1
if (count > (video_length-1)):
time_end = time.time()
cap.release()
print "Done extracting frames.\n%d frames extracted" %count
print "It took %d seconds for conversion." %(time_end-time_start)
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment