Repository navigation
Expand file tree
/
Copy pathvideo.py
More file actions
202 lines (161 loc) · 6.29 KB
/
Copy pathvideo.py
File metadata and controls
202 lines (161 loc) · 6.29 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
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import types
from pathlib import Path
from typing import Union
import av
import cv2
from decord import VideoReader, cpu
from moviepy import ImageSequenceClip, VideoFileClip
from assertpy.assertpy import assert_that
def video_info(path: Union[Path, str], reader: str = "opencv"):
assert_that(path).is_file().is_readable()
assert_that(reader).is_in("opencv", "moviepy", "pyav", "decord")
if reader == "opencv":
video = cv2.VideoCapture(str(path))
width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = video.get(cv2.CAP_PROP_FPS)
n_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
duration = n_frames / fps if fps > 0 else 0.0
video.release()
elif reader == "moviepy":
clip = VideoFileClip(str(path))
width = clip.w
height = clip.h
fps = clip.fps
n_frames = clip.reader.nframes
duration = clip.duration
clip.close()
elif reader == "pyav":
with av.open(str(path)) as container:
stream = container.streams.video[0]
width = stream.width
height = stream.height
fps = float(stream.average_rate) if stream.average_rate else 0.0
n_frames = stream.frames
duration = n_frames / fps if fps > 0 else 0.0
elif reader == "decord":
with open(str(path), "rb") as f:
video_reader = VideoReader(f, ctx=cpu(0))
n_frames = len(video_reader)
fps = video_reader.get_avg_fps()
height, width = video_reader[0].asnumpy().shape[:2]
duration = n_frames / fps if fps > 0 else 0.0
return {
"width": width,
"height": height,
"fps": fps,
"n_frames": n_frames,
"duration": duration,
}
def video_writer_like(
path: Union[Path, str], target: Union[Path, str], format: str = "mp4"
):
assert_that(path).is_file().is_readable()
assert_that(format).is_in("mp4")
fourcc_formats = {"mp4": "mp4v"}
fourcc_format = fourcc_formats[format]
fourcc = cv2.VideoWriter_fourcc(*fourcc_format)
info = video_info(path)
width = info["width"]
height = info["height"]
fps = info["fps"]
return cv2.VideoWriter(
str(target),
fourcc,
fps,
(width, height),
)
def video_frames(path: Union[Path, str], reader: str = "opencv", bgr2rgb: bool = True):
"""
Generator function that yields frames from a video file using different video readers.
Args:
- path (Union[Path, str]): Path to the video file.
- reader (str, optional): Specifies the video reader library to use. Default is "opencv".
Available options: "opencv", "moviepy", "pyav", "decord".
- bgr2rgb (bool, optional): If True, converts BGR formatted frames to RGB. Default is True.
Yields:
- ndarray: Frames from the video file in RGB format (if specified) or in the original format.
Raises:
- AssertionError: If the path is not a readable file or if an invalid video reader is provided.
"""
assert_that(path).is_file().is_readable()
assert_that(reader).is_in("opencv", "moviepy", "pyav", "decord")
if reader == "opencv":
cap = cv2.VideoCapture(str(path))
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
yield cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) if bgr2rgb else frame
cap.release()
elif reader == "moviepy":
with VideoFileClip(str(path)) as clip:
for frame in clip.iter_frames():
yield frame
elif reader == "pyav":
with av.open(str(path)) as container:
for frame in container.decode(video=0):
yield frame.to_ndarray(format="rgb24")
elif reader == "decord":
with open(path, "rb") as f:
video_reader = VideoReader(f, ctx=cpu(0))
for i in range(len(video_reader)):
yield video_reader[i].asnumpy()
def frames_to_video(
frames: Union[list, types.GeneratorType],
target: Union[Path, str] = "video.mp4",
writer: str = "opencv",
fps: float = 30.0,
codec: str = "mp4v",
rgb2bgr: bool = True,
) -> None:
assert_that(writer).is_in("opencv", "moviepy", "pyav")
assert_that(Path(target).parent).is_directory().is_readable()
if writer == "opencv":
if isinstance(frames, types.GeneratorType):
first_frame = next(frames, None)
if first_frame is None:
return
else:
if len(frames) == 0:
return
first_frame = frames[0]
fourcc = cv2.VideoWriter_fourcc(*codec)
height, width = first_frame.shape[:2]
video_writer = cv2.VideoWriter(
str(target),
fourcc,
fps,
(width, height),
)
convert = lambda frame: cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
# If frames is a generator, the first frame has been
# extracted above (next(frames, None)), so it should be written
if isinstance(frames, types.GeneratorType):
video_writer.write(convert(first_frame) if rgb2bgr else first_frame)
for frame in frames:
video_writer.write(convert(frame) if rgb2bgr else frame)
video_writer.release()
elif writer == "moviepy":
frames = list(frames)
if len(frames) > 0:
ImageSequenceClip(frames, fps=fps).write_videofile(str(target), logger=None)
else:
print(f"Video {str(target)} not written because frames are empty.")
elif writer == "pyav":
frames = list(frames)
if len(frames) == 0:
print(f"Video {str(target)} not written because frames are empty.")
return
height, width = frames[0].shape[:2]
with av.open(str(target), "w") as container:
stream = container.add_stream("h264", rate=fps)
stream.width = width
stream.height = height
stream.pix_fmt = "yuv420p"
for frame in frames:
video_frame = av.VideoFrame.from_ndarray(frame, format="rgb24")
for packet in stream.encode(video_frame):
container.mux(packet)
for packet in stream.encode():
container.mux(packet)