|
import os |
|
import csv |
|
import yt_dlp as youtube_dl |
|
import cv2 |
|
from moviepy.editor import VideoFileClip |
|
|
|
def download_and_extract_frames(csv_file, output_base_folder='video_frames'): |
|
|
|
os.makedirs(output_base_folder, exist_ok=True) |
|
|
|
|
|
with open(csv_file, 'r') as file: |
|
csv_reader = csv.reader(file) |
|
|
|
next(csv_reader, None) |
|
|
|
|
|
for row in csv_reader: |
|
try: |
|
video_name, video_link = row |
|
|
|
|
|
safe_video_name = ''.join(c if c.isalnum() or c in ['-', '_'] else '_' for c in video_name) |
|
|
|
|
|
ydl_opts = { |
|
'outtmpl': f'./{safe_video_name}.%(ext)s', |
|
'format': 'bestvideo+bestaudio/best', |
|
'no_color': True, |
|
'no_warnings': True |
|
} |
|
|
|
|
|
with youtube_dl.YoutubeDL(ydl_opts) as ydl: |
|
ydl.download([video_link]) |
|
|
|
|
|
downloaded_files = os.listdir('.') |
|
video_files = [f for f in downloaded_files if f.startswith(safe_video_name) and |
|
(f.endswith('.mp4') or f.endswith('.webm') or f.endswith('.mkv'))] |
|
|
|
if not video_files: |
|
print(f"Error: No video file found for {video_name}") |
|
continue |
|
|
|
|
|
frame_folder = os.path.join(output_base_folder, safe_video_name) |
|
os.makedirs(frame_folder, exist_ok=True) |
|
|
|
|
|
for video_file in video_files: |
|
|
|
video = cv2.VideoCapture(video_file) |
|
frame_count = 0 |
|
|
|
while True: |
|
ret, frame = video.read() |
|
if not ret: |
|
break |
|
|
|
|
|
frame_path = os.path.join(frame_folder, f'frame_{frame_count:04d}.jpg') |
|
cv2.imwrite(frame_path, frame) |
|
frame_count += 1 |
|
|
|
|
|
video.release() |
|
|
|
print(f"Processed {video_name} from {video_file}: {frame_count} frames extracted") |
|
|
|
except Exception as e: |
|
print(f"Error processing {video_name}: {str(e)}") |
|
|
|
continue |
|
|
|
|
|
if __name__ == "__main__": |
|
download_and_extract_frames('videos.csv') |