1+ import cv2
2+ from tqdm import tqdm
3+
4+ class FrameExtractor :
5+ def __init__ (self , video_path ) :
6+ self .video_path = video_path
7+ self .min_frame = None
8+ self .max_frame = None
9+ self .frame_number = None
10+
11+ def extract_frames (self , min_frame = None , max_frame = None ):
12+ self .min_frame = min_frame
13+ self .max_frame = max_frame
14+ video = cv2 .VideoCapture (self .video_path )
15+
16+ total_frames = int (video .get (cv2 .CAP_PROP_FRAME_COUNT ))
17+
18+ if self .min_frame is None and self .max_frame is None :
19+ self .min_frame = 0
20+ self .max_frame = total_frames - 1
21+
22+ if self .min_frame < 0 or self .max_frame > total_frames or self .min_frame >= self .max_frame :
23+ print (f"Invalid frame range. Video has { total_frames } frames." )
24+ return
25+
26+ pbar = tqdm (total = self .max_frame - self .min_frame + 1 , desc = "Extracting frames ..." , unit = "frame" )
27+
28+ frame_count = 0
29+ extracted_frames = 0
30+ while True :
31+ success , frame = video .read ()
32+
33+ if not success :
34+ break
35+
36+ if self .min_frame <= frame_count <= self .max_frame :
37+ cv2 .imwrite (f"frames/frame_{ frame_count } .jpg" , frame )
38+ extracted_frames += 1
39+ pbar .update (1 )
40+
41+ frame_count += 1
42+
43+ if frame_count > self .max_frame :
44+ break
45+
46+ pbar .close ()
47+ video .release ()
48+ print (f"Extracted { extracted_frames } frames from frame { self .min_frame } to { self .max_frame } ." )
49+
50+ def extract_single_frame (self , frame_number ):
51+ self .frame_number = frame_number
52+ video = cv2 .VideoCapture (self .video_path )
53+
54+ total_frames = int (video .get (cv2 .CAP_PROP_FRAME_COUNT ))
55+
56+ if self .frame_number < 0 or self .frame_number >= total_frames :
57+ print (f"Invalid frame number. Video has { total_frames } frames." )
58+ return
59+
60+ video .set (cv2 .CAP_PROP_POS_FRAMES , self .frame_number )
61+
62+ success , frame = video .read ()
63+
64+ if success :
65+ cv2 .imwrite (f"frames/frame_{ self .frame_number } .jpg" , frame )
66+ print (f"Extracted and saved frame { self .frame_number } as frame_{ self .frame_number } .jpg" )
67+ else :
68+ print (f"Could not extract frame { self .frame_number } ." )
69+
70+ video .release ()
0 commit comments