Skip to content
Advertisement

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

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()

Advertisement

Answer

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)
Advertisement