-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcapture_circular_stream.py
More file actions
73 lines (63 loc) · 2.02 KB
/
capture_circular_stream.py
File metadata and controls
73 lines (63 loc) · 2.02 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
#!/usr/bin/python3
import socket
import threading
import time
import numpy as np
from picamera2 import Picamera2
from picamera2.encoders import H264Encoder
from picamera2.outputs import CircularOutput, FileOutput
lsize = (320, 240)
picam2 = Picamera2()
video_config = picam2.create_video_configuration(main={"size": (1280, 720), "format": "RGB888"},
lores={"size": lsize, "format": "YUV420"})
picam2.configure(video_config)
picam2.start_preview()
encoder = H264Encoder(1000000, repeat=True)
circ = CircularOutput()
encoder.output = [circ]
picam2.encoders = encoder
picam2.start()
picam2.start_encoder()
w, h = lsize
prev = None
encoding = False
ltime = 0
def server():
global circ, picam2
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("0.0.0.0", 10001))
sock.listen()
while tup := sock.accept():
event = threading.Event()
conn, addr = tup
stream = conn.makefile("wb")
filestream = FileOutput(stream)
filestream.start()
encoder.output = [circ, filestream]
filestream.connectiondead = lambda _: event.set() # noqa
event.wait()
t = threading.Thread(target=server)
t.setDaemon(True)
t.start()
while True:
cur = picam2.capture_buffer("lores")
cur = cur[:w * h].reshape(h, w)
if prev is not None:
# Measure pixels differences between current and
# previous frame
mse = np.square(np.subtract(cur, prev)).mean()
if mse > 7:
if not encoding:
epoch = int(time.time())
circ.fileoutput = f"{epoch}.h264"
circ.start()
encoding = True
print("New Motion", mse)
ltime = time.time()
else:
if encoding and time.time() - ltime > 5.0:
circ.stop()
encoding = False
prev = cur
picam2.stop_encoder()