-
Notifications
You must be signed in to change notification settings - Fork 6
/
interface.py
447 lines (355 loc) · 15.7 KB
/
interface.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
from PyQt5 import QtCore, QtGui, QtWidgets, uic
import sys
import cv2
import numpy as np
import threading
import time
import queue
import re
from recordsave import Recorder
from ssd_engine import SSD_Detector
from motiondetector import MotionDetector
from settings import EmailSender
# Title
WINDOW_TITLE = "DeepEye v1.1 2018"
# Cam Params
CAM_INDEX = 0
CAM_WIDTH = 1280
CAM_HEIGHT = 720
CAM_FPS = 30
# (record everything mode) This parameter determines the intervals of recording
RECORD_INTERVAL = 120 # in seconds
# (smart recording mode) This parameter determines how many more frames to save after inactivity
RECORD_EXTENSION = 60 # in frame counts
# Threading variables
cam_running = False
capture_thread = None
q = queue.Queue()
# load UI
form_class = uic.loadUiType("interface.ui")[0]
# parallel threaded camera feed
def grab(cam, queue, width, height, fps):
global cam_running
cam_running = True
capture = cv2.VideoCapture(cam)
capture.set(cv2.CAP_PROP_FRAME_WIDTH, width)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
capture.set(cv2.CAP_PROP_FPS, fps)
while(cam_running):
frame = {}
capture.grab()
retval, img = capture.retrieve(0)
frame["img"] = img
if queue.qsize() < 10:
queue.put(frame)
else:
print (queue.qsize())
print("Terminated camera feed")
class MyWindowClass(QtWidgets.QMainWindow, form_class):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.setFixedSize(self.size())
# obtain dim of elements
self.triggerGroupDim = [self.triggerGroup.geometry().width(),self.triggerGroup.geometry().height()]
self.recordButtonDim = [self.recordButton.geometry().width(),self.recordButton.geometry().height()]
self.filepathTextDim = [self.filepathText.geometry().width(),self.filepathText.geometry().height()]
# Livefeed tab:
self.window_width = self.live_display.frameSize().width()
self.window_height = self.live_display.frameSize().height()
self.live_display.setStyleSheet("QLabel { background-color : black}")
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.update_frame)
self.timer.start(1)
self.datetimeTagLocation = (10,30)
self.datetimeTagColour = (0,255,0)
# Recorder object
self.record = Recorder(CAM_WIDTH, CAM_HEIGHT, CAM_FPS)
self.recordButton.clicked.connect(self.record_to)
self.timetracker = -1
self.subjectCheck.stateChanged.connect(self.record_on_detection)
self.recordOnPresence = False
self.inactiveCount = 0
self.isDetected = False
self.motionCheck.stateChanged.connect(self.record_on_motion)
self.recordOnMotion = False
self.isMoving = False
self.noMotionCount = 0
self.motionTagLocation = (CAM_WIDTH-300,30)
self.motionTagColour = (0,0,255)
# Detector object
self.detector = SSD_Detector()
if not self.detector.ready:
self.subjectCheck.setEnabled(False)
# Motion detector object
self.motiondetect = MotionDetector()
# email alert module
self.emailsender = EmailSender()
self.sendOnActivity = False
self.sendoutStartTime = -1
self.emailsetupButton.clicked.connect(self.emailAlertSetup)
self.testemailButton.clicked.connect(self.emailSendTest)
self.sendemailCheck.stateChanged.connect(self.emailSendToggleFunc)
self.password_input.setEchoMode(QtWidgets.QLineEdit.Password)
self.port_input.setValidator(QtGui.QIntValidator(0,999))
if self.emailsender.getSetupFlag():
email_address, email_password, smtp, port = self.emailsender.getLoginDetails()
self.email_input.setText(email_address)
self.password_input.setText(email_password)
self.smtp_input.setText(smtp)
self.port_input.setText(str(port))
# Disable user interface
self.emailGroup.setEnabled(False)
self.testemailButton.setEnabled(True)
self.sendemailCheck.setEnabled(True)
self.emailsetupButton.setText("Change")
def emailSendToggleFunc(self):
if self.sendemailCheck.isChecked():
self.sendOnActivity = True
else:
self.sendOnActivity = False
self.sendoutStartTime = -1
def emailSendTest(self):
if self.emailsender.getSetupFlag():
self.emailsender.send_testmsg()
def emailAlertSetup(self):
if self.emailsetupButton.text() == "Setup":
if not self.emailsender.getSetupFlag():
email_address = self.email_input.text()
email_password = self.password_input.text()
smtp = self.smtp_input.text()
port = self.port_input.text()
# simple check to evaluate input validity
check_email_pattern = re.compile('[^@]+@[^@]+\.[^@]+')
if not check_email_pattern.match(email_address):
self.err_email_label.setText("Invalid Email")
else:
self.err_email_label.setText("")
self.emailsender.login_setup(email_address,email_password,smtp,int(port))
if self.emailsender.getSetupFlag():
# If successfully logged in
self.emailGroup.setEnabled(False)
self.testemailButton.setEnabled(True)
self.sendemailCheck.setEnabled(True)
self.emailsetupButton.setText("Change")
else:
# authentication failed
self.err_email_label.setText("Authentication Failed!")
else:
self.emailsender.close_connection()
self.emailGroup.setEnabled(True)
self.testemailButton.setEnabled(False)
self.sendemailCheck.setEnabled(False)
self.emailsetupButton.setText("Setup")
def emailSendTracker(self, isDetected):
currentDateTime = QtCore.QTime.currentTime().toString(QtCore.Qt.DefaultLocaleLongDate).split()
currentDayLight = currentDateTime[1]
currentTime = currentDateTime[0].split(':')
currentTimeSeconds = int(currentTime[0])*3600 + int(currentTime[1])*60 + int(currentTime[2])
if isDetected:
if self.sendoutStartTime == -1: # initialize
# send out first email here
print("Activity started: Send out first email")
self.emailsender.send_emailalert(True,currentTimeSeconds,currentDayLight)
self.sendoutStartTime = currentTimeSeconds
else:
# invoke timeout sequence (2 mins of inactivity, send out last email)
if self.sendoutStartTime > -1:
if currentTimeSeconds - self.sendoutStartTime > RECORD_INTERVAL:
print("Activity ended: Send out last email")
self.emailsender.send_emailalert(False,currentTimeSeconds,currentDayLight)
self.sendoutStartTime = -1
def resizeEvent(self,event):
# readjust ui according to window size
# MainWindow.textEdit.setGeometry(QtCore.QRect(30, 80, 341, 441))
curr_mainframe_w = self.frameSize().width()
curr_mainframe_h = self.frameSize().height()
# Adjust tab widget size
fixed_tab_x = self.tabWidget.geometry().x()
fixed_tab_y = self.tabWidget.geometry().y()
new_tab_w = curr_mainframe_w - 40
new_tab_h = curr_mainframe_h - 80
self.tabWidget.resize(new_tab_w,new_tab_h)
# **** Set all elements relative to tabWidget_relativeSizeRatio ****
# set triggerGroup Pos:
new_trigger_x = fixed_tab_x + (new_tab_w - self.triggerGroupDim[0] - 40)
new_trigger_y = fixed_tab_y
self.triggerGroup.move(new_trigger_x,new_trigger_y)
# set recordButton Pos:
new_recordbtn_x = fixed_tab_x + (new_tab_w/2 - self.recordButtonDim[0])
new_recordbtn_y = fixed_tab_y + (new_tab_h - self.recordButtonDim[1] - 80)
self.recordButton.move(new_recordbtn_x,new_recordbtn_y)
# set filePath Pos:
new_filepath_x = fixed_tab_x
new_filepath_y = new_recordbtn_y - self.filepathTextDim[1] - 20
self.filepathText.move(new_filepath_x,new_filepath_y)
# finally set the display size
self.window_width = new_trigger_x - 40
self.window_height = new_filepath_y - 40
self.live_display.resize(self.window_width,self.window_height)
def record_to(self):
if self.record.getPreDefinedFilePath() == "undefined":
# return filepath where video is saved
dir_ = QtWidgets.QFileDialog.getExistingDirectory(None, 'Select a folder for record output:', '~/', QtWidgets.QFileDialog.ShowDirsOnly)
if len(dir_) > 0:
self.record.setPreDefinedFilePath(dir_)
self.filepathText.setText('Saving video to: ' + dir_)
else:
self.record.setPreDefinedFilePath("undefined")
else:
if self.record.getRecordingStatus():
# stop recording
self.record.turnOffRecording()
self.recordButton.setText('Record')
else:
self.record.invokeRecording()
if self.record.getRecordingStatus():
self.recordButton.setText('Stop')
def record_on_detection(self):
if self.subjectCheck.isChecked():
self.recordOnPresence = True
else:
self.recordOnPresence = False
def record_on_motion(self):
if self.motionCheck.isChecked():
self.recordOnMotion = True
else:
self.recordOnMotion = False
def recordTriggerFunc(self, frame):
# record on presence only
if self.recordOnPresence and not self.recordOnMotion:
if self.isDetected:
if self.inactiveCount >= RECORD_INTERVAL: # estimate 2 sec of detect nothing
self.record.invokeRecording() #reinitalize
self.record.vidWriter.write(frame)
self.inactiveCount = 0
else:
if self.inactiveCount < RECORD_INTERVAL:
self.inactiveCount += 1
else:
self.record.killRecorder()
elif self.recordOnMotion and not self.recordOnPresence:
if self.isMoving:
if self.noMotionCount >= RECORD_INTERVAL:
self.record.invokeRecording()
self.record.vidWriter.write(frame)
self.noMotionCount = 0
else:
if self.noMotionCount < RECORD_INTERVAL:
self.noMotionCount += 1
else:
self.record.killRecorder()
elif self.recordOnMotion and self.recordOnPresence:
if self.isDetected or self.isMoving:
if self.inactiveCount >= RECORD_INTERVAL and self.noMotionCount >= RECORD_INTERVAL:
self.record.invokeRecording()
self.record.vidWriter.write(frame)
self.inactiveCount = 0
self.noMotionCount = 0
else:
assessOne = False
assessTwo = False
if self.noMotionCount < RECORD_INTERVAL:
self.noMotionCount += 1
else:
assessOne = True
if self.inactiveCount < RECORD_INTERVAL:
self.inactiveCount += 1
else:
assessTwo = True
if assessOne and assessTwo:
self.record.killRecorder()
else:
# Record everything in interval of 2 minutes
if self.timetracker == -1:
self.timetracker = self.record.getCurrentTime()
else:
ref_hr, ref_min, ref_sec, _ = self.timetracker.split('_')
refTimeInSeconds = int(ref_min)*60 + int(ref_sec)
cur_hr, cur_min, cur_sec, _ = self.record.getCurrentTime().split('_')
curTimeInSeconds = int(cur_min)*60 + int(cur_sec)
if curTimeInSeconds - refTimeInSeconds >= RECORD_INTERVAL:
self.record.invokeRecording()
self.timetracker = self.record.getCurrentTime()
self.record.vidWriter.write(frame)
def drawOnFrame(self, inputImg, isMotion):
# Tag date
cv2.putText(inputImg,self.record.getDisplayLabel(),
self.datetimeTagLocation,
cv2.FONT_HERSHEY_SIMPLEX,
1,
self.datetimeTagColour,
2,
cv2.LINE_AA)
# Tag motion indicator
if isMotion:
cv2.putText(inputImg,"Motion Detected!",
self.motionTagLocation,
cv2.FONT_HERSHEY_SIMPLEX,
1,
self.motionTagColour,
2,
cv2.LINE_AA)
def displayFrame(self, img):
img_height, img_width, img_colors = img.shape
scale_w = float(self.window_width) / float(img_width)
scale_h = float(self.window_height) / float(img_height)
scale = min([scale_w, scale_h])
if scale == 0:
scale = 1
img = cv2.resize(img, None, fx=scale, fy=scale, interpolation = cv2.INTER_CUBIC)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
height, width, bpc = img.shape
bpl = bpc * width
image = QtGui.QImage(img.data, width, height, bpl, QtGui.QImage.Format_RGB888)
pix = QtGui.QPixmap(image)
self.live_display.setPixmap(pix)
# Live Mode
def update_frame(self):
if not q.empty():
# UI thingy
self.recordButton.setEnabled(True)
# grab frame from video thread
try:
frame = q.get()
img = frame["img"]
except:
print("error obtaining images")
else:
# detect motion
if self.recordOnMotion:
# detect motion
motionImg = img.copy()
self.isMoving = self.motiondetect.detectmotion(motionImg)
else:
self.isMoving = False
# detect presence
if self.recordOnPresence:
# detect objects and indicate on display
img, self.isDetected = self.detector.process_image(img)
else:
self.isDetected = False
if self.sendOnActivity:
if self.isMoving or self.isDetected:
self.emailSendTracker(True)
else:
self.emailSendTracker(False)
# Tag the frame with indications
self.drawOnFrame(img,self.isMoving)
if self.record.getRecordingStatus():
self.recordTriggerFunc(img)
# show frame with annotation
self.displayFrame(img)
def closeEvent(self, event):
global cam_running
cam_running = False
self.record.killRecorder()
def main():
capture_thread = threading.Thread(target=grab, args = (CAM_INDEX, q, CAM_WIDTH, CAM_HEIGHT, CAM_FPS))
capture_thread.start()
app = QtWidgets.QApplication(sys.argv)
w = MyWindowClass(None)
w.setWindowTitle(WINDOW_TITLE)
w.show()
app.exec_()
main()