-
Notifications
You must be signed in to change notification settings - Fork 1
/
ffwriter.py
71 lines (53 loc) · 1.42 KB
/
ffwriter.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
import numpy as np
import cv2
import subprocess
class NullFile(object):
def fileno(self):
return 0
def write(self, data):
pass
class FFWriter(object):
def __init__(self, fname, fps, (width, height), codec='libx264', pixfmt=None, moreflags=''):
self.width = width
self.height = height
self.proc = subprocess.Popen([
"ffmpeg",
'-loglevel', 'warning',
'-f', 'rawvideo',
'-pix_fmt', pixfmt or 'bgr24',
'-s', '{0}x{1}'.format(width, height),
'-r', '{0}'.format(fps),
'-i', 'pipe:0',
'-c:v', codec,
] + (moreflags.split() if isinstance(moreflags, str) else moreflags) + [
'-y',
fname
], stdin=subprocess.PIPE) #, stderr=NullFile())
def isOpened(self):
return True
def write(self, frame):
assert frame.dtype == np.uint8
assert frame.shape[2] in (3, 4)
assert frame.shape[0] == self.height
assert frame.shape[1] == self.width
frame.tofile(self.proc.stdin)
def close(self):
self.proc.stdin.close()
return self.proc.wait()
def release(self):
self.close()
def __del__(self):
self.close()
if __name__ == '__main__':
#frame = np.zeros((1080, 1920,3), dtype=np.uint8)
cam = cv2.VideoCapture(0)
rv,frame = cam.read()
# https://www.ffmpeg.org/ffmpeg-codecs.html#libx264_002c-libx264rgb
vid = FFWriter("test.mov", 25, frame.shape[1::-1], '-crf 15 -preset ultrafast')
vid.write(frame)
try:
while True:
rv,frame = cam.read()
vid.write(frame)
finally:
vid.close()