I would like to extract the first frame (or 1st to nth) of each video from multiple video files in a folder and save it as an image.
If it is just one video file, I have achieved it below, but I am not sure how to process multiple video files.
You may not understand the basics, but I appreciate your cooperation.
import cv2
video_path="E:\UserX\Test\Trial1.mp4"
cap=cv2.VideoCapture(video_path)
for num in range(1): # You can specify the number of images to be retrieved by changing the number of numbers
cap.set (cv2.CAP_PROP_POS_FRAMES, num)
cv2.imwrite("E:\UserX\Test\picture{:0=4}".format(num)+".tif", cap.read()[1])
print("save picture {:0=4}".format(num)+".tif")
cap.release()
I wrote the code as below.In this way, the file path should be '/Users/~/sample'+str(i+1)+'mp4'.Also, you need to create any folder to save the frame image extracted outside (line 4). I'm still studying, so I can't write it well, but I hope it will be helpful.
import cv2
import os#add
img_outdir='./img'#addressed
os.madeirs(img_outdir,exist_ok=True)#Added
number=len(os.listdir('Path of Folder containing Movie Files')# Add
for i in range (number): # Add
movie_file='filepath'+str(i+1)+'file format'#add
cap=cv2.VideoCapture(movie_file)
for num in range(1): # You can specify the number of images to be retrieved by changing the number of numbers
cap.set (cv2.CAP_PROP_POS_FRAMES, num)
ouimg_file="{}/{:05d}.jpg".format(img_outdir, i+1)#Added
cv2.imwrite("E:\UserX\Test\picture{:0=4}".format(num)+".tif", cap.read()[1])
print("save picture {:0=4}".format(num)+".tif")
cap.release()
1031 Uncaught (inpromise) Error on Electron: An object could not be cloned
861 GDB gets version error when attempting to debug with the Presense SDK (IDE)
991 M2 Mac fails to install rbenv install 3.1.3 due to errors
1510 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2025 OneMinuteCode. All rights reserved.