Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

utils.py 1.9 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  1. import os
  2. import math
  3. import datetime
  4. import matplotlib.pyplot as plt
  5. import cv2
  6. class FrameExtractor():
  7. """
  8. Class used for extracting frames from a video file.
  9. """
  10. def __init__(self, video_path):
  11. self.video_path = video_path
  12. self.vid_cap = cv2.VideoCapture(video_path)
  13. self.n_frames = int(self.vid_cap.get(cv2.CAP_PROP_FRAME_COUNT))
  14. self.fps = int(self.vid_cap.get(cv2.CAP_PROP_FPS))
  15. def get_video_duration(self):
  16. duration = self.n_frames/self.fps
  17. print(f"Duration: {datetime.timedelta(seconds=duration)}")
  18. def get_n_images(self, every_x_frame):
  19. n_images = math.floor(self.n_frames / every_x_frame) + 1
  20. print(f"Extracting every {every_x_frame} (nd/rd/th) frame would result in {n_images} images.")
  21. def extract_frames(self, every_x_frame, img_name, skip_seconds, dest_path=None, img_ext = ".jpg"):
  22. if not self.vid_cap.isOpened():
  23. self.vid_cap = cv2.VideoCapture(self.video_path)
  24. if dest_path is None:
  25. dest_path = os.getcwd()
  26. else:
  27. if not os.path.isdir(dest_path):
  28. os.mkdir(dest_path)
  29. print(f"Created the following directory: {dest_path}")
  30. frame_cnt = 0
  31. img_cnt = 0
  32. while self.vid_cap.isOpened():
  33. success,image = self.vid_cap.read()
  34. if frame_cnt > (skip_seconds * self.fps):
  35. if not success:
  36. break
  37. if frame_cnt % every_x_frame == 0:
  38. img_path = os.path.join(dest_path, "".join([img_name, "_", str(img_cnt), img_ext]))
  39. cv2.imwrite(img_path, image)
  40. img_cnt += 1
  41. frame_cnt += 1
  42. self.vid_cap.release()
  43. cv2.destroyAllWindows()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...