exetract.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import cv2
  2. import time
  3. import os
  4. def video_to_frames(input_loc, output_loc):
  5. """Function to extract frames from input video file
  6. and save them as separate frames in an output directory.
  7. Args:
  8. input_loc: Input video file.
  9. output_loc: Output directory to save the frames.
  10. Returns:
  11. None
  12. """
  13. try:
  14. os.mkdir(output_loc)
  15. except OSError:
  16. pass
  17. # Log the time
  18. time_start = time.time()
  19. # Start capturing the feed
  20. cap = cv2.VideoCapture(input_loc)
  21. # Find the number of frames
  22. video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1
  23. print("Number of frames: ", video_length)
  24. count = 0
  25. print("Converting video..\n")
  26. # Start converting the video
  27. while cap.isOpened():
  28. # Extract the frame
  29. ret, frame = cap.read()
  30. if not ret:
  31. continue
  32. # Write the results back to output location.
  33. cv2.imwrite(output_loc + "/%#05d.jpg" % (count+1), frame)
  34. count = count + 1
  35. # If there are no more frames left
  36. if (count > (video_length-1)):
  37. # Log the time again
  38. time_end = time.time()
  39. # Release the feed
  40. cap.release()
  41. # Print stats
  42. print("Done extracting frames.\n%d frames extracted" % count)
  43. print("It took %d seconds forconversion." % (time_end-time_start))
  44. break