Video analysis: download, keyframes, transcripts, thumbnail grids and AI summaries of what's on screen.

0 downloads

dbbasic-video/src/dbbasic_video/extract_keyframes.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-video.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-video.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-video.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Update README with live PyPI link c32f6df 1 year, 1 month ago History
extract_keyframes.py · 3.7 KB · 131 lines
1#!/usr/bin/env python3
2"""
3Scene Detection and Keyframe Extraction
4Extracts a keyframe from each scene change in a video file.
5"""
6
7import argparse
8import os
9from pathlib import Path
10from scenedetect import VideoManager, SceneManager
11from scenedetect.detectors import ContentDetector
12from scenedetect.frame_timecode import FrameTimecode
13import cv2
14
15
16def extract_keyframes(video_path, output_dir, threshold=27.0):
17 """
18 Detect scenes in a video and extract keyframes.
19
20 Args:
21 video_path: Path to input video file
22 output_dir: Directory to save keyframe images
23 threshold: Scene detection threshold (lower = more sensitive)
24
25 Returns:
26 List of tuples (scene_number, frame_path, timecode)
27 """
28 # Create output directory
29 output_path = Path(output_dir)
30 output_path.mkdir(parents=True, exist_ok=True)
31
32 # Initialize video manager and scene manager
33 video_manager = VideoManager([video_path])
34 scene_manager = SceneManager()
35 scene_manager.add_detector(ContentDetector(threshold=threshold))
36
37 # Start video processing
38 video_manager.set_downscale_factor()
39 video_manager.start()
40
41 print(f"Processing video: {video_path}")
42 print(f"Detecting scenes with threshold: {threshold}")
43
44 # Detect scenes
45 scene_manager.detect_scenes(frame_source=video_manager)
46 scene_list = scene_manager.get_scene_list()
47
48 print(f"\nDetected {len(scene_list)} scenes")
49
50 # Extract keyframes
51 video_cap = cv2.VideoCapture(video_path)
52 fps = video_cap.get(cv2.CAP_PROP_FPS)
53
54 keyframes = []
55
56 for i, scene in enumerate(scene_list):
57 scene_num = i + 1
58 # Get the start frame of the scene
59 start_frame = scene[0].get_frames()
60 start_time = scene[0].get_seconds()
61
62 # Set video to the frame
63 video_cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
64 ret, frame = video_cap.read()
65
66 if ret:
67 # Save keyframe
68 filename = f"scene_{scene_num:04d}_frame_{start_frame:06d}.jpg"
69 filepath = output_path / filename
70 cv2.imwrite(str(filepath), frame)
71
72 keyframes.append((scene_num, str(filepath), start_time))
73 print(f"Scene {scene_num}: {filename} @ {start_time:.2f}s")
74
75 video_cap.release()
76 video_manager.release()
77
78 print(f"\nExtracted {len(keyframes)} keyframes to {output_dir}")
79
80 # Save metadata
81 metadata_path = output_path / "scenes_metadata.txt"
82 with open(metadata_path, 'w') as f:
83 f.write(f"Video: {video_path}\n")
84 f.write(f"Scenes detected: {len(scene_list)}\n")
85 f.write(f"Threshold: {threshold}\n\n")
86 for scene_num, filepath, timecode in keyframes:
87 f.write(f"Scene {scene_num}: {Path(filepath).name} @ {timecode:.2f}s\n")
88
89 print(f"Metadata saved to {metadata_path}")
90
91 return keyframes
92
93
94def main():
95 parser = argparse.ArgumentParser(
96 description="Extract keyframes from scene changes in a video"
97 )
98 parser.add_argument(
99 "video",
100 help="Path to input video file"
101 )
102 parser.add_argument(
103 "-o", "--output",
104 default="keyframes",
105 help="Output directory for keyframes (default: keyframes)"
106 )
107 parser.add_argument(
108 "-t", "--threshold",
109 type=float,
110 default=27.0,
111 help="Scene detection threshold, lower = more sensitive (default: 27.0)"
112 )
113
114 args = parser.parse_args()
115
116 # Check if video exists
117 if not os.path.exists(args.video):
118 print(f"Error: Video file not found: {args.video}")
119 return 1
120
121 # Extract keyframes
122 try:
123 extract_keyframes(args.video, args.output, args.threshold)
124 return 0
125 except Exception as e:
126 print(f"Error: {e}")
127 return 1
128
129
130if __name__ == "__main__":
131 exit(main())