-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ropey-Cam.py
executable file
·332 lines (282 loc) · 12.2 KB
/
Ropey-Cam.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
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#!/usr/bin/python3
#Rev01 Control button functionality updated as per initial Circular Buffer version
# Run this script, then point a web browser at http:<this-ip-address>:8000
# or to test on the local machine use 127.0.0.1:8000
# While running, any motion above 'TriggerLevel'will start a timestamped video capture to
# a local Videos subfolder, along with an optional jpeg monochrome still of the trigger moment.
# Adjust TriggerLevel as required to set sensitivity of trigger
# Based almost entirely on examples from Picamera2 manual and githhub examples stitched together
# Buttons on home page can :Start/Stop streaming: :Delete Video Files: :RESET: :Spare Button4: :Reboot the system: or :Toggle motion triggering:
# Other features ????
import os
import logging
import socketserver
import numpy as np
import simplejpeg
import cv2
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Condition, Thread
from picamera2 import Picamera2, MappedArray
from picamera2.encoders import MJPEGEncoder
from picamera2.encoders import H264Encoder
from picamera2.outputs import FfmpegOutput
from picamera2.outputs import FileOutput
from datetime import datetime
from PIL import Image
from libcamera import Transform
from libcamera import controls
# Set initial value of HTML 'variables'
Message1="This will be the Feedback Message Area"
Stop_Start="STOP"
MotionBtn ="Mot_OFF"
w,h=1024,768 #Set default recorded video dimensions
w2,h2=w//2,h//2 #Half size lo-res size for motion detect and streaming
#Initialise variables and Booleans
TriggerLevel=15
trigger=TriggerLevel # Sensitivity of frame to frame change for motion detection
video_count=0
Motoggle=True
wasbuttonpressed=False
Reboot = False
DeleteFiles = False
#Pick a Camera Mode
cam_mode_select =5 # Pick the most suitable mode for your sensor
# set text colour, position and size for timestamp
colour = (240, 240, 30)
origin = (180, 50)
font = cv2.FONT_HERSHEY_SIMPLEX
scale = 2
thickness = 2
# Make sure that we're in the right directory and then check for
# and, if necessary create a Videos subdirectory and move into it
full_path=os.path.realpath(__file__)
thisdir = os.path.dirname(full_path)
os.chdir (thisdir)
if not os.path.isdir ("Videos"):
os.mkdir("Videos")
os.chdir("Videos")
os.environ["LIBCAMERA_LOG_LEVELS"] = "4" #reduce libcamera messsages
def apply_timestamp(request):
timestamp = time.strftime("%Y-%m-%d %X")
with MappedArray(request, "main") as m:
cv2.putText(m.array, timestamp, origin, font, scale, colour, thickness)
def capturebuffer():
global cb_frame
global buf2
while not cb_abort:
buf2 = picam2.capture_array("lores")
with cb_condition:
cb_frame = buf2
cb_condition.notify_all()
#mjpeg encode a frame based on example. Can this be improved upon with better/hardware encoder ??
def mjpeg_encode():
global mjpeg_frame
while not mjpeg_abort:
with cb_condition:
cb_condition.wait()
yuv = cb_frame
rgb = cv2.cvtColor(yuv, cv2.COLOR_YUV420p2RGB)
buf = simplejpeg.encode_jpeg(rgb, quality=70, colorspace='BGR', colorsubsampling='420')
with mjpeg_condition:
mjpeg_frame = buf
mjpeg_condition.notify_all()
class StreamingHandler(BaseHTTPRequestHandler):
def do_POST(self):
global Message1,Stop_Start,wasbuttonpressed,MotionBtn,TriggerLevel,video_count,Reboot,DeleteFiles
content_length = int(self.headers['Content-Length']) # Get the size of data
post_data = self.rfile.read(content_length).decode("utf-8") # Get the data
post_data = post_data.split("=")[1] # Only keep the value
if post_data == 'START':
Message1="Start was pressed so next action is Stop"
Stop_Start="STOP"
picam2.start_recording(H264Encoder(), encoder.output)
elif post_data == 'STOP':
Message1="Stop was pressed so next action is Start"
Stop_Start="START"
picam2.stop_recording()
elif post_data == 'DELETE':
Message1="Press DELETE again to delete all files - or RESET to cancel"
if DeleteFiles:
os.system("rm avi*")
video_count=0
DeleteFiles =False
Message1 = "Video files deleted and counter reset"
else:
DeleteFiles=True
elif post_data =='RESET':
Message1="Reset DELETE and REBOOT to initial default conditions"
Reboot=False
DeleteFiles=False
elif post_data == 'Button4':
Message1="Button 4 was pressed"
elif post_data == 'REBOOT':
Message1=" Press REBOOT again if you're sure - or RESET to cancel"
if Reboot:
os.system("sudo reboot")
Reboot = True
elif post_data == 'Mot_ON':
Message1="Motion_ON was pressed so next action is Motion_OFF"
MotionBtn="Mot_OFF"
TriggerLevel=trigger
elif post_data == 'Mot_OFF':
Message1="Motion_OFF was pressed so next action is Motion_ON"
MotionBtn="Mot_ON"
TriggerLevel=9999999
print("Control button pressed was {}".format(post_data))
wasbuttonpressed =True
self._redirect('/index.html') # Redirect back to the home url
def _redirect(self, path):
self.send_response(303)
self.send_header('Content-type', 'text/html')
self.send_header('Location', path)
self.end_headers()
def do_GET(self):
global mjpeg_condition
PAGE = """\
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ropey-Cam</title>
</head>
<body>
<center>
<h2>Ropey-Cam Streamer and motion-triggered Recorder</h2>
<img src="stream.mjpg" width="800" height="600" />
<p> {ph1} </p>
<form action="/" method="POST">
<input type="submit" name="submit" value="{ph2}">
<input type="submit" name="submit" value="DELETE">
<input type="submit" name="submit" value="RESET">
<input type="submit" name="submit" value="Button4">
<input type="submit" name="submit" value="REBOOT">
<input type="submit" name="submit" value="{ph3}">
</form>
</center>
</body>
</html>
""".format(ph1=Message1,ph2=Stop_Start, ph3=MotionBtn)
if self.path == '/':
self.send_response(301)
self.send_header('Location', '/index.html')
self.end_headers()
elif self.path == '/index.html':
content = PAGE.encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('Content-Length', len(content))
self.end_headers()
self.wfile.write(content)
elif self.path == '/stream.mjpg':
self.send_response(200)
self.send_header('Age', 0)
self.send_header('Cache-Control', 'no-cache, private')
self.send_header('Pragma', 'no-cache')
self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
self.end_headers()
try:
while True:
with mjpeg_condition:
mjpeg_condition.wait()
frame = mjpeg_frame
self.wfile.write(b'--FRAME\r\n')
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-Length', len(frame))
self.end_headers()
self.wfile.write(frame)
self.wfile.write(b'\r\n')
except Exception as e:
logging.warning(
'Removed streaming client %s: %s',
self.client_address, str(e))
else:
self.send_error(404)
self.end_headers()
class StreamingServer(socketserver.ThreadingMixIn, HTTPServer):
allow_reuse_address = True
daemon_threads = True
def motion():
global video_count, wasbuttonpressed
prev = None
encoding = False
ltime = 0
start_time=0
if not wasbuttonpressed:# Ignore motion check if button was recently pressed
while True:
with cb_condition:
cb_condition.wait()
cur = cb_frame
cur = cur[:h2,:]
if prev is not None:
mse = np.mean(np.square(np.subtract(cur, prev)))
#uncomment next line to get a running printout of background video change level
#print(mse)
if mse >TriggerLevel: #Adjust TriggerLevel for motion sensivity and /or noise level in image
if not encoding:
video_count+=1
now = datetime.now()
date_time = now.strftime("%Y%m%d_%H%M%S")
file_title="avi_{:05d}_{}".format(video_count,date_time)
# Store a monochrome image of trigger point.
#Comment out next two lines if not required
#icon=Image.fromarray(cur)
#icon.save(file_title+"_im.jpg")
encoder.output= FfmpegOutput(file_title+".mp4")
picam2.start_encoder(encoder)
encoding = True
start_time = time.time()
print()
print(f'New motion detected with a "change value" of {mse:.0f}')
ltime = time.time()
else:
if (encoding and time.time() - ltime > 5.0) :
picam2.stop_encoder(encoder)
encoding = False
print("Saving file",file_title)
print(f'which holds { (time.time()-start_time):.0f} seconds worth of video')
print()
print("Waiting for next trigger")
prev = cur
wasbuttonpressed = False
def stream():
try:
address = ('', 8000)
server = StreamingServer(address, StreamingHandler)
server.serve_forever()
finally:
mjpeg_abort = True
mjpeg_thread.join()
picam2 = Picamera2()
mode=picam2.sensor_modes[cam_mode_select]
picam2.configure(picam2.create_video_configuration(sensor={"output_size":mode['size'],'bit_depth':mode['bit_depth']},
controls={'FrameDurationLimits' : (33333,1000000)},
transform=Transform(hflip=True,vflip=True),
main={"size": (w,h)},
lores={"size": (w2, h2)},buffer_count=10))
encoder = H264Encoder(1900000, repeat=True,iperiod=45)
picam2.pre_callback = apply_timestamp
picam2.start()
#Start the various threads
cb_abort = False
cb_frame = None
buf2 = None
cb_condition = Condition()
cb_thread = Thread(target=capturebuffer, daemon=True)
cb_thread.start()
mjpeg_abort = False
mjpeg_frame = None
mjpeg_condition = Condition()
mjpeg_thread = Thread(target=mjpeg_encode, daemon=True)
mjpeg_thread.start()
stream_thread = Thread(target=stream, daemon=True)
stream_thread.start()
motion_thread = Thread(target=motion, daemon=True)
motion_thread.start()
motion_thread.join()
#Join motion thread to ensure recordings are given priority and complete uninterrupted -?? Maybe??
#Unnecessary joins?
#mjpeg_thread.join()
#stream_thread.join()
#cb_thread.join()