stage4 / videos_gen_images.py
Wangpeng An
Upload folder using huggingface_hub
b619216 verified
import os
import cv2
import concurrent.futures
def extract_frames_from_folder(folder_path):
def extract_frame(video_path):
# Open video file
video_capture = cv2.VideoCapture(video_path)
# Jump to the 6th frame
frame_number = 6
video_capture.set(cv2.CAP_PROP_POS_FRAMES, frame_number - 1)
# Read the 6th frame
success, frame = video_capture.read()
if success:
# Get the video file name (without extension)
video_name = os.path.splitext(os.path.basename(video_path))[0]
# Set the image save path to the original video path
image_path = os.path.join(os.path.dirname(video_path), f"{video_name}.jpg")
# Check if the image file already exists
if not os.path.exists(image_path):
cv2.imwrite(image_path, frame)
# print(f"Saved frame {frame_number} as {image_path}")
else:
print(f"Image already exists for {video_name}")
else:
print(f"Unable to read frame {frame_number}")
# Release the video file
video_capture.release()
# Collect video files
video_files = []
for root, dirs, files in os.walk(folder_path):
for filename in files:
if filename.lower().endswith(".mp4") or filename.lower().endswith(".mkv"):
video_files.append(os.path.join(root, filename))
# Extract frames using multiple threads
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
executor.map(extract_frame, video_files)
# Call the function with your folder path
folder_path = "videochatgpt_tune" # Replace with your folder path
extract_frames_from_folder(folder_path)