PrashanthB461 commited on
Commit
4c80c04
·
verified ·
1 Parent(s): 153c5f0

Create extract_frames.py

Browse files
Files changed (1) hide show
  1. safety_analyzer/extract_frames.py +70 -0
safety_analyzer/extract_frames.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ```python
2
+ import cv2
3
+ import os
4
+ import logging
5
+ import argparse
6
+
7
+ # Setup logging
8
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
9
+ logger = logging.getLogger(__name__)
10
+
11
+ def extract_frames(video_path, output_dir, frame_interval=30):
12
+ try:
13
+ os.makedirs(output_dir, exist_ok=True)
14
+ logger.info(f"Output directory: {output_dir}")
15
+
16
+ video = cv2.VideoCapture(video_path)
17
+ if not video.isOpened():
18
+ raise ValueError(f"Could not open video: {video_path}")
19
+
20
+ fps = video.get(cv2.CAP_PROP_FPS)
21
+ total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
22
+ logger.info(f"Video: {video_path}, FPS: {fps}, Total frames: {total_frames}")
23
+
24
+ frame_count = 0
25
+ saved_count = 0
26
+ video_name = os.path.splitext(os.path.basename(video_path))[0]
27
+
28
+ while True:
29
+ ret, frame = video.read()
30
+ if not ret:
31
+ break
32
+
33
+ if frame_count % frame_interval == 0:
34
+ frame_path = os.path.join(output_dir, f"{video_name}_frame_{frame_count}.jpg")
35
+ cv2.imwrite(frame_path, frame)
36
+ saved_count += 1
37
+ logger.info(f"Saved frame: {frame_path}")
38
+
39
+ frame_count += 1
40
+
41
+ video.release()
42
+ logger.info(f"Extracted {saved_count} frames from {video_path}")
43
+ except Exception as e:
44
+ logger.error(f"Error extracting frames from {video_path}: {e}")
45
+ raise
46
+
47
+ def main():
48
+ parser = argparse.ArgumentParser(description="Extract frames from videos for training dataset.")
49
+ parser.add_argument("--video-dir", default="videos", help="Directory containing input videos")
50
+ parser.add_argument("--output-dir", default="dataset/images/train", help="Directory to save extracted frames")
51
+ parser.add_argument("--frame-interval", type=int, default=30, help="Extract every nth frame")
52
+ args = parser.parse_args()
53
+
54
+ video_dir = args.video_dir
55
+ output_dir = args.output_dir
56
+ frame_interval = args.frame_interval
57
+
58
+ if not os.path.exists(video_dir):
59
+ logger.error(f"Video directory does not exist: {video_dir}")
60
+ return
61
+
62
+ for video_file in os.listdir(video_dir):
63
+ if video_file.endswith((".mp4", ".avi", ".mov")):
64
+ video_path = os.path.join(video_dir, video_file)
65
+ extract_frames(video_path, output_dir, frame_interval)
66
+
67
+ if __name__ == "__main__":
68
+ logger.info("Starting frame extraction...")
69
+ main()
70
+ ```