-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
83 lines (64 loc) · 2.24 KB
/
utils.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
import pathlib
from os import makedirs
from os.path import exists, join
import imageio_ffmpeg
import yaml
def write_args(args, dir):
if dir:
with open(dir / "args.yml", "w") as outfile:
yaml.dump(args, outfile, default_flow_style=False)
def make_filepath(base_dir, dir, filename, force=False):
if dir is not None:
print(dir)
dir_ = base_dir / dir
print(dir_)
if not exists(dir_):
makedirs(dir_)
assert exists(dir_)
if filename:
filepath = dir_ / filename
if exists(f"{filepath}.npz") and not force:
print("File exists!")
exit()
return filepath
else:
return dir_
class VideoRenderStream:
"""A stream for writing images to a video."""
def __init__(self, video_name, output_root_path, fps=20, frame_size=(1024, 784)):
"""Initialize and open the video file to stream videos to.
The caller is responsible for closing the stream. This object
is best used in a python `with` statement.
"""
# construct output path
self.output_root_path = output_root_path
self.video_path = self.output_root_path / video_name
# video parameters
self.fps = fps
self.frame_size = frame_size # (width, height)
# initialize the video rendering pipeline
self.video_path.parent.mkdir(exist_ok=True)
self.video_writer = imageio_ffmpeg.write_frames(
str(self.video_path), fps=self.fps, size=self.frame_size
)
self.video_writer.send(None)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def close(self):
"""Closes the video stream to no longer allow writing video data."""
if self.video_writer is not None:
self.video_writer.close()
self.video_writer = None
def write(self, image):
"""Write an image to the video."""
self.video_writer.send(image)
class NullContext:
"""Dummy context manager."""
def __init__(self):
pass
def __enter__(self):
return None
def __exit__(self, exc_type, exc_val, exc_tb):
pass