-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsample_frames.py
159 lines (131 loc) · 6.17 KB
/
sample_frames.py
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#!/usr/bin/env python
"""Defines the sample_frames function
This function select sequence of frames from a video
"""
import os
import cv2
import numpy as np
from PIL import Image
def sample_frames(sample_type, video_path, max_frames, frame_sample_rate, clip_size, segment_secs=None, all_fragments=None):
"""Samples video frames reduces computational effort. Taking max_frames frames at equal intervals
"""
assert os.path.exists(video_path), 'video path {} doesn\'t exist'.format(video_path)
try:
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS)
if segment_secs is not None:
start, end = tuple(segment_secs)
start_index = start * fps # int(max(start - .5, 0) * fps)
stop_index = end * fps # int(max(end - .5, 0) * fps)
cap.set(cv2.CAP_PROP_POS_FRAMES, start_index)
else:
start_index = 0
stop_index = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
frame_count = stop_index - start_index
except Exception as e:
print('Cannot process {} because {}'.format(video_path, e))
pass
else:
frames, frames_ts, fragments_mask = [], [], []
index, calc_timestamp = start_index, 0
while index < stop_index:
ret, frame = cap.read()
if ret is not True:
break
timestamp = cap.get(cv2.CAP_PROP_POS_MSEC) / 1000
if all_fragments is not None:
mark = 0
for f in all_fragments:
start, end = tuple(f)
if timestamp >= start and timestamp <= end:
mark = 1
fragments_mask.append(mark)
# Convert the BGR image into an RGB image, because the later model uses the RGB format.
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = Image.fromarray(frame)
frames.append(frame)
frames_ts.append(timestamp)
index += 1
if not len(frames):
print('video-clip without frames in segment: {}, fragments: {}'.format(segment_secs, all_fragments))
return [], [], [], 0, []
#assert len(frames), 'video-clip without frames in segment: {}, fragments: {}'.format(segment_secs, all_fragments)
# frames = np.array(frames)
# print(fragments_mask, all_fragments)
if sample_type == 'dynamic':
frames_per_side = frame_sample_rate // 2
if frame_sample_rate * max_frames < len(frames):
indices = np.linspace(frames_per_side, len(frames) - frames_per_side + 1, max_frames, endpoint=False, dtype=int)
elif frame_sample_rate < len(frames):
indices = list(range(frames_per_side, len(frames) - frames_per_side, frame_sample_rate))
else:
indices = [len(frames)//2]
elif sample_type == 'fixed':
# sample max_frames frames always
indices = np.linspace(0, len(frames), max_frames, endpoint=False, dtype=int)
# clip_list = [frames[max(i - clip_size//2, 0): i + clip_size//2, len(frames))] for i in indices]
clip_list = []
for i in indices:
ss = max(i - clip_size//2, 0)
to = min(i + clip_size//2, len(frames))
if ss == 0:
to = min(clip_size, len(frames))
elif to == len(frames):
ss = max(len(frames) - clip_size, 0)
clip_list.append(frames[ss:to])
frame_list = [frames[i] for i in indices]
frame_ts_list = [frames_ts[i] for i in indices]
if all_fragments is not None:
fragments_mask = [fragments_mask[i] for i in indices]
# if frame_sample_rate == -1:
# indices = np.linspace(frames_per_side, len(frames) - frames_per_side + 1, max_frames, endpoint=False, dtype=int)
# clip_list = [frames[i - frames_per_side: i + frames_per_side] for i in indices]
# else:
# frames_per_side = frame_sample_rate // 2
# sample_step = frame_sample_rate - frame_sample_overlap
# max_index = len(frames) - frames_per_side
# indices = []
# i = frames_per_side
# while i <= max_index and len(indices) < max_frames:
# indices.append(i)
# i += sample_step
# clip_list = [frames[i - frames_per_side: i + frames_per_side] for i in indices]
# clip_list = np.array(clip_list)
# frame_list = frames[indices]
# frame_list = [frames[i] for i in indices]
return frame_list, frame_ts_list, clip_list, len(frames), fragments_mask
def sample_frames2(video_path, num_segments, segment_length):
"""Samples video frames reduces computational effort. Taking max_frames frames at equal intervals
"""
assert os.path.exists(video_path), 'video path {} doesn\'t exist'.format(video_path)
try:
cap = cv2.VideoCapture(video_path)
except Exception as e:
print('Can not open {} because {}'.format(video_path, e))
pass
else:
frames = []
i = 0
while True:
ret, frame = cap.read()
if ret is not True:
break
# Convert the BGR image into an RGB image, because the later model uses the RGB format.
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frames.append(frame)
frames = np.array(frames)
num_frames = len(frames)
if num_frames > num_segments + segment_length - 1:
tick = (num_frames - segment_length + 1) / float(num_segments)
offsets = np.array([int(tick / 2.0 + tick * x) for x in range(num_segments)])
else:
offsets = np.zeros((num_segments,))
offsets+=1
images = []
for seg_ind in offsets:
p = int(seg_ind)
for i in range(segment_length):
images.append(frames[p])
if p < num_frames:
p += 1
return images, num_frames