My question is:
Can I extract image frames from a large number of videos all at once using OpenCV Python and save it in a folder in the form of .jpg or .png?
I have written an OpenCV Python code which extracts image frames from 1 video when I provide the video path of that video as the input. Also I have provided the output path of the image frames extracted to a different directory. But, my code can take 1 video path at once and extract image frames from that video.
Is there any way, where I can provide a path of the directory having 'n' number of videos and I can extract the image frames from all those n videos at a time in a sequential order and save it in the output path directory?
Below is my Python code using OpenCV module for extracting image frames from a single video.
import cv2
import os
video_path = 'C:/Users/user/Videos/abc.mp4' # video name
output_path = 'C:/Users/user/Pictures/image_frames' # location on ur pc
if not os.path.exists(output_path):
os.makedirs(output_path)
cap = cv2.VideoCapture(video_path)
index = 0
while cap.isOpened():
Ret, Mat = cap.read()
if Ret:
index += 1
if index % 29 != 0:
continue
cv2.imwrite(output_path + '/' + str(index) + '.png', Mat)
else:
break
cap.release()
Assuming that you code is correct, you can create a function with your code, list files in directory and pass then to your function.
import cv2
import os
# your function
def video2frames( video_file, output_path )
if not os.path.exists(output_path):
os.makedirs(output_path)
cap = cv2.VideoCapture(video_path)
index = 0
while cap.isOpened():
Ret, Mat = cap.read()
if Ret:
index += 1
if index % 29 != 0:
continue
cv2.imwrite(output_path + '/' + str(index) + '.png', Mat)
else:
break
cap.release()
return
def multiple_video2frames( video_path, output_path )
list_videos = os.listdir(video_path)
for video in list_videos:
video_base = os.path.basename(video)
input_file = video_path + '/' + video
out_path = output_path + '/' + video_base
video2frames(input_file, out_path)
return
# run all
video_path = 'C:/Users/user/Videos/' # all videos
output_path = 'C:/Users/user/Pictures/' # location on ur pc
multiple_video2frames( video_path, output_path )