How do I run my Python OpenCV code on all video files in a folder?

Question:

I have written some python code for extracting two frames from a video file using OpenCV. I have tested my code and it works for one video file.

However, I have a folder with hundreds of video files and I would like to extract two frames from all the videos in that folder. Is there a method of doing this for all the files in a folder? Perhaps using the os module or something similar?

My code is below for reference:

    import cv2
    import numpy as np
    import os

    # Playing video from file:
    cap = cv2.VideoCapture('/Users/batuhanyildirim/Desktop/UCF-
    101/BenchPress/v_benchPress_g25_c07_mp4.m4v')

    try:
        if not os.path.exists('data'):
            os.makedirs('data')
    except OSError:
        print('Error: Creating directory of data')

    currentFrame = 0

    while(True):
        # Capture frame by frame
        ret, frame = cap.read()

        # Only take the first frame and tenth frame
        if currentFrame == 0:
            # Saves image of the current frame in jpg file
            name = './data/frame' + str(currentFrame) + '.jpg'
            print ('Creating...' + name)
            cv2.imwrite(name, frame)

        if currentFrame == 5:
            name = './data/frame' + str(currentFrame) + '.jpg'
            print ('Creating...' + name)
            cv2.imwrite(name, frame)

        # To stop duplicate images
        currentFrame += 1

    cap.release()
    cv2.destroyAllWindows()
Asked By: seabass09

||

Answers:

Just make it function ad call it in a for loop for every video

import cv2
import numpy as np
import os

def frame_capture(file):
  # Playing video from file:
  cap = cv2.VideoCapture(file)

  try:
      if not os.path.exists('data'):
          os.makedirs('data')
  except OSError:
      print('Error: Creating directory of data')

  currentFrame = 0

  while(True):
      # Capture frame by frame
      ret, frame = cap.read()

      # Only take the first frame and tenth frame
      if currentFrame == 0:
          # Saves image of the current frame in jpg file
          name = './data/frame' + str(currentFrame) + '.jpg'
          print ('Creating...' + name)
          cv2.imwrite(name, frame)

      if currentFrame == 5:
          name = './data/frame' + str(currentFrame) + '.jpg'
          print ('Creating...' + name)
          cv2.imwrite(name, frame)

      # To stop duplicate images
      currentFrame += 1

  cap.release()
  cv2.destroyAllWindows()

for the loop:

import os
for file in os.listdir("/mydir"):
    if file.endswith(".m4v"):
        path=os.path.join("/mydir", file))
        frame_capture(path)
Answered By: Stavros Avramidis

The selected answer was great but it ran for like more than a hour for me, so I created directory and set it as my working one in a step before this code and then added a ‘break’ after the last if statement in the above code. That did the trick!

    import cv2
    import numpy as np
    import os

    def frame_capture(file):
        # Playing video from file:
       cap = cv2.VideoCapture(file)

      currentFrame = 0

      while(True):
          # Capture frame by frame
          ret, frame = cap.read()

            # Only take the tenth frame

          if currentFrame == 5:
              name = './data/frame' + str(currentFrame) + '.jpg'
              print ('Creating...' + name)
              cv2.imwrite(name, frame)
              break

              # To stop duplicate images
          currentFrame += 1

      cap.release()
      cv2.destroyAllWindows()
Answered By: Cur123
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.