-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvideo_processor.py
More file actions
84 lines (61 loc) · 3.04 KB
/
video_processor.py
File metadata and controls
84 lines (61 loc) · 3.04 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import cv2
import numpy as np
import os
class VideoProcessor:
def __init__(self):
self.supported_formats = ['mp4', 'avi', 'mov', 'mkv', 'wmv', 'flv']
def extract_thumbnail(self, video_path, thumbnail_size=(300, 300)):
try:
if not os.path.exists(video_path):
print(f"Video not found: {video_path}")
return None
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Failed to open video: {video_path}")
return None
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print(f"Video {video_path} has {total_frames} frames")
if total_frames > 0:
frame_position = total_frames // 2
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_position)
ret, frame = cap.read()
if not ret:
print(f"Failed to read middle frame, trying first frame for {video_path}")
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ret, frame = cap.read()
cap.release()
if not ret or frame is None:
print(f"Failed to read any frame from {video_path}")
return None
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w = frame.shape[:2]
if h > thumbnail_size[0] or w > thumbnail_size[1]:
scale = min(thumbnail_size[0] / h, thumbnail_size[1] / w)
new_h, new_w = int(h * scale), int(w * scale)
frame = cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_AREA)
print(f"Successfully extracted thumbnail from {video_path}, size: {frame.shape}")
return frame
except Exception as e:
print(f"Error extracting thumbnail from {video_path}: {e}")
return None
def extract_first_frame(self, video_path, thumbnail_size=(300, 300)):
try:
if not os.path.exists(video_path):
return None
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
return None
ret, frame = cap.read()
cap.release()
if not ret or frame is None:
return None
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w = frame.shape[:2]
if h > thumbnail_size[0] or w > thumbnail_size[1]:
scale = min(thumbnail_size[0] / h, thumbnail_size[1] / w)
new_h, new_w = int(h * scale), int(w * scale)
frame = cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_AREA)
return frame
except Exception as e:
print(f"Error extracting first frame from {video_path}: {e}")
return None