This little Code Snippet allows you to extract frames from one or multiple videos.
import os
import numpy as np
import cv2
from glob import glob
os.chdir('d:\\your\\path')
def create_dir(path):
try:
if not os.path.exists(path):
os.makedirs(path)
except OSError:
print(f"ERROR: creating dir with name {path}")
To do so we use the CV2 package
def save_frame(video_path, save_dir, gap=100): #specify the gap
name = video_path.split("/")[-1].split(".")[0]
save_path = os.path.join(save_dir, name)
create_dir(save_path)
cap = cv2.VideoCapture(video_path)
idx = 0 # this is the zero frame
while True:
ret, frame = cap.read()
if ret == False:
cap.release()
break
if idx == 0:
cv2.imwrite(f"{save_path}/{idx}.png", frame)
else:
if idx % gap == 0:
cv2.imwrite(f"{save_path}/{idx}.png", frame)
idx += 1
if __name__ == "__main__":
video_paths = glob("videos/*")
save_dir = "save"
for path in video_paths:
save_frame(path, save_dir, gap=100) #specify the gap
Now just put the videos you want to extract frames from in the video folder. Make sure the directory is set correctly and run the script. The output you will find in the save folder.
Here is a demo gif. Hope this will work for you too and happy coding :)
This project is inspired by https://github.com/nikhilroxtomar.