Amazing-Python-Scripts
95 строк · 3.0 Кб
1import os
2from os import path
3import math
4import cv2
5import argparse
6
7
8class Extractor:
9"""Extract frames from video file and saves them in a directory
10
11Arguments:
12vid_filename {str} -- Location of video file
13output_dir {str} -- Output directory to store frames
14
15
16"""
17
18global args
19
20def __init__(self, vid_filename, output_dir, verbose=False):
21
22self.verbose = verbose
23self.output_dir = output_dir
24if not os.path.exists(self.output_dir):
25os.makedirs(self.output_dir)
26print(self.output_dir)
27if path.exists(vid_filename):
28self.vid_filename = vid_filename
29else:
30raise FileNotFoundError(f"File {vid_filename} not found")
31
32# initialize video capture
33self.cap = cv2.VideoCapture(self.vid_filename)
34
35# get video fps
36self.fps = self.cap.get(cv2.CAP_PROP_FPS)
37
38# Video length in frames
39self.vid_length = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
40
41def extractor(self):
42is_ok, frame = self.cap.read()
43count = 0
44print(self.fps)
45while is_ok:
46# is_ok, frame = self.cap.read()
47print(
48f"Extracting frame {count} of {self.vid_length-1}") if self.verbose else {}
49# save current frame
50cv2.imwrite(os.path.join(
51self.output_dir, f"{count}.jpg"), frame)
52print("COMPLETED") if count == self.vid_length-1 else {}
53
54is_ok, frame = self.cap.read()
55
56count += 1
57
58def extract_frames(file):
59global args
60
61# check whether file is greather than 0 bytes using path
62if os.stat(path.join(args.input_dir, file)).st_size > 0:
63# extract frames
64extractor = Extractor(path.join(args.input_dir, file), path.join(
65args.output_dir, file), args.sampling_rate)
66extractor.extractor()
67else:
68print(f"File {file} is empty")
69
70
71def main():
72# setup parsers for CLI arguments
73parser = argparse.ArgumentParser("Frame Extractor")
74parser.add_argument("-i", "--video_file", type=str,
75help="Location of video file", required=True)
76parser.add_argument("-o", "--output_dir", type=str,
77help="Output directory to store frames", required=True)
78parser.add_argument("-v", "--verbose", type=bool,
79help="Display details of extraction of frames", default=False)
80args = parser.parse_args()
81# print(args)
82# Extract frames from video file
83if args.video_file:
84name = args.video_file.split(".")[0]
85ext = args.video_file.split(".")[1]
86if ext != "mp4":
87raise argparse.ArgumentTypeError(
88f"File {args.video_file} is not a video(.mp4) file")
89output_dir = os.path.join(args.output_dir, name)
90extract = Extractor(args.video_file, args.output_dir, args.verbose)
91extract.extractor()
92
93
94if __name__ == '__main__':
95main()
96