-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
224 lines (187 loc) · 8.22 KB
/
app.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
import telegram
import datetime
import time
import math
import cv2
import os
import re
import queue
import threading
import numpy as np
import socket
from utils import Utils
class HomeCamBot():
def __init__(self):
self.botToken = os.environ['BOT_TOKEN']
self.chat_id = os.environ['CHAT_ID']
self.bot = telegram.Bot(token=self.botToken)
self.HeartBeatSent = False
def SendPhoto(self, img, msg):
message = self.bot.sendPhoto(photo=img, caption=msg, chat_id=self.chat_id)
return message
def SendMessage(self, message):
self.bot.sendMessage(chat_id=self.chat_id, text=message)
self.HeartBeatSent = True
class Detector():
def __init__(self):
self.modelConfiguration = "yolo/coco_yolov3-tiny.cfg"
self.modelWeights = "yolo/coco_yolov3-tiny.weights"
self.net = cv2.dnn.readNetFromDarknet(self.modelConfiguration, self.modelWeights)
self.net.getLayerNames()
self.layerOutput = self.net.getUnconnectedOutLayersNames()
self.net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
self.net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
self.target_w = 416
self.target_h = 416
self.classes = None
self.classesFile = "yolo/coco.names"
with open(self.classesFile, 'rt') as f:
self.classes = f.read().rstrip('\n').split('\n')
self.include_objects = ["person", "laptop", "keyboard", "cell phone", "tvmonitor", "knife"]
self.util_lib = Utils()
def detect(self, frame):
blob = cv2.dnn.blobFromImage(frame,
1.0/255,
(self.target_w, self.target_h),
(0, 0, 0), swapRB=True, crop=False)
# predict classess & box
self.net.setInput(blob)
output = self.net.forward(self.layerOutput)
t, _ = self.net.getPerfProfile()
print('inference time: %.2f s' % (t / cv2.getTickFrequency()))
return self.util_lib.postprocess(output, frame, self.classes, self.include_objects)
class CustomVideoCapture():
def __init__(self, name):
self.name = name
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(5)
self.cap = None
self.initializeVideoCapture()
self.q = queue.Queue()
t = threading.Thread(target=self._reader)
t.daemon = True
t.start()
def urlParse(self, uri):
p = '(?:http.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*'
m = re.search(p, uri)
return m.group('host'), int(m.group('port'))
def checkMjpeg(self):
host, port = self.urlParse(self.name)
result = self.sock.connect_ex((host, port))
return result == 0 # true is open, otherwise is closed
def initializeVideoCapture(self):
self.cap = None
retry_failed_counter = 0
while self.cap == None :
try :
if not self.checkMjpeg() :
time.sleep(30)
retry_failed_counter += 1
raise Exception("MJPEG source is not available : ", self.name)
self.cap = cv2.VideoCapture(self.name )
print("[INFO] New camera started!")
except cv2.error as e:
print("[ERROR] ' (cv error) error when initialize camera,' ", e)
time.sleep(1)
except Exception as e:
print("[ERROR] 'error when initialize camera,' ", e)
time.sleep(1)
if retry_failed_counter > 3 :
print("[ERROR] 'retry_failed_counter' exceeded, throw an exeption and stop retrying.")
self.cap = DummyVideoCapture()
def _reader(self):
while self.cap.isOpened() :
try :
ret, frame = self.cap.read()
if not ret :
self.cap.release()
print("[INFO] Invalid image!")
print("[INFO] Restart camera in 30 seconds!")
time.sleep(30)
print("[INFO] Initialize new camera!")
self.initializeVideoCapture()
continue
if not self.q.empty():
try:
self.q.get_nowait()
except queue.Empty:
pass
self.q.put(frame)
except cv2.error as e:
print("[ERROR] ' (cv error) error when read frame from camera,' ", e)
time.sleep(1)
except Exception as e:
print("[ERROR] 'error when read frame from camera,' ", e)
time.sleep(1)
def read(self):
try :
return True, self.q.get()
except Exception as e:
print("[ERROR] Custom Video Capture read,", e)
return False, None
def isOpened(self):
return self.cap.isOpened()
def release(self):
return self.cap.release()
class DummyVideoCapture():
def isOpened(self):
return False
class CameraStream():
def __init__(self, cap_source):
self.cap_source = cap_source
self.cap = CustomVideoCapture(self.cap_source)
self.cam_bot = HomeCamBot()
self.detector = Detector()
self.lastFaceSent = 0
self.lastDetectedPoint = [0, 0]
self.minDetectedDist = 50 # less than this distance will be classified as same object and no longer be sent again to telegram
def checkAboveDetectedDist(self, pt):
aboveDetectedDist = math.dist(pt, self.lastDetectedPoint) >= self.minDetectedDist
if (aboveDetectedDist) :
self.lastDetectedPoint = pt
return aboveDetectedDist
def run(self):
while self.cap.isOpened() :
ret, img = self.cap.read()
try :
HasObject, detected_objects, img = self.detector.detect(img)
if HasObject and (time.time() - self.lastFaceSent) > 5:
if (self.checkAboveDetectedDist(detected_objects[0].get('pt'))) :
self.lastFaceSent = time.time()
TimeStr = datetime.datetime.now().strftime("%H:%M:%S")
object_str = " ".join(["%d %s," % (i.get('count'), i.get('name')) for i in detected_objects])
msg = "Detected %s in image at %s" % (object_str, TimeStr)
imgPath = "image/photo.jpg"
cv2.imwrite(imgPath, img)
try :
message = self.cam_bot.SendPhoto(open(imgPath, 'rb'), msg)
print("[INFO] Detecting object, send image to Telegram with message :\n%s\n" % message)
except Exception as e:
print("[ERROR] 'error when send to telegram,' ", e)
else :
print("[INFO] 'detected object with no movement, image will not sent to telegram' ")
try :
CurrTime = datetime.datetime.now()
if CurrTime.minute in {0, 30} :
if not self.cam_bot.HeartBeatSent:
self.cam_bot.SendMessage("[INFO] heart beat msg, camera %s status : %r " % (os.environ['CAMERA_NAME'], self.cap.isOpened()))
else :
self.cam_bot.HeartBeatSent = False
except Exception as e:
print("[ERROR] 'error when send to telegram,' ", e)
except Exception as e:
print("[ERROR] ", e)
else :
self.cap.release()
print("Camera Closed!")
self.cam_bot.SendMessage("[INFO] heart beat msg, camera %s status : CAMERA CLOSED " % (os.environ['CAMERA_NAME']))
if __name__ == '__main__':
print("\n\n---- Object Detection service starting! ----\n\n")
cap_source = os.environ['MJPEG_URL']
i = 0
while i < 3 :
stream = CameraStream(cap_source)
stream.run()
time.sleep(60)
print("\n\n[INFO] Retry (%d) to open camera in %s \n\n" % (i, datetime.datetime.now().strftime("%H:%M:%S")))
i += 1