forked from intel-iot-devkit/people-counter-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_jupyter.py
213 lines (180 loc) · 7.5 KB
/
main_jupyter.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
"""People Counter."""
"""
Copyright (c) 2018 Intel Corporation.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit person to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import os
import sys
import time
import socket
import json
import cv2
import subprocess
import logging as log
import paho.mqtt.client as mqtt
from inference import Network
# MQTT server environment variables
HOSTNAME = socket.gethostname()
IPADDRESS = socket.gethostbyname(HOSTNAME)
MQTT_HOST = IPADDRESS
MQTT_PORT = 1884
MQTT_KEEPALIVE_INTERVAL = 60
try:
# Probability threshold for detections filtering
prob_threshold = float(os.environ['PROB_THRESHOLD'])
except:
prob_threshold = 0.5
def performance_counts(perf_count):
"""
print information about layers of the network.
:param perf_count: Dictionary describing the status of the layers
:return: None
"""
print("{:<70} {:<15} {:<15} {:<15} {:<10}".format('name', 'layer_type',
'exec_type', 'status',
'real_time, us'))
for layer, stats in perf_count.items():
print("{:<70} {:<15} {:<15} {:<15} {:<10}".format(layer,
stats['layer_type'],
stats['exec_type'],
stats['status'],
stats['real_time']))
def ssd_parser(frame, result):
"""
parses the ssd output
:param frame: frame from camera/video
:param result: list contains the data to parse ssd
:return: person count and frame
"""
current_count = 0
for obj in result[0][0]:
# Draw bounding box for object when it's probability is more
# than the specified threshold
if float(obj[2]) > float(prob_threshold):
xmin = int(obj[3] * initial_w)
ymin = int(obj[4] * initial_h)
xmax = int(obj[5] * initial_w)
ymax = int(obj[6] * initial_h)
cv2.rectangle(frame, (xmin, ymin), (xmax, ymax),
(0, 55, 255), 1)
current_count = current_count + 1
return frame, current_count
def main():
"""
Load the network and parse the SSD output.
:return: None
"""
# Connect to the MQTT server
client = mqtt.Client()
client.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)
log.basicConfig(format="[ %(levelname)s ] %(message)s", level=log.INFO,
stream=sys.stdout)
# Flag for the input image
single_image_mode = False
cur_request_id = 0
last_count = 0
total_count = 0
start_time = 0
model = os.environ['MODEL']
device = os.environ['DEVICE'] if 'DEVICE' in os.environ.keys() else 'CPU'
cpu_extension = os.environ[
'CPU_EXTENSION'] if 'CPU_EXTENSION' in os.environ.keys() else None
# Checks for live feed
if os.environ['INPUT'] == 'CAM':
input_stream = 0
# Checks for input image
elif os.environ['INPUT'].endswith('.jpg') or os.environ['INPUT'].endswith('.bmp'):
single_image_mode = True
input_stream = os.environ['INPUT']
# Checks for video file
else:
input_stream = os.environ['INPUT']
assert os.path.isfile(os.environ['INPUT']), "Specified input file doesn't exist"
cap = cv2.VideoCapture(input_stream)
if input_stream:
cap.open(os.environ['INPUT'])
if not cap.isOpened():
log.error("ERROR! Unable to open video source")
# Initialise the class
infer_network = Network()
# Load the network to IE plugin to get shape of input layer
n, c, h, w = infer_network.load_model(model, device, 1, 1,
cur_request_id, cpu_extension)[1]
global initial_w,initial_h
initial_w = cap.get(3)
initial_h = cap.get(4)
fps = cap.get(cv2.CAP_PROP_FPS)
cmdstring = ('ffmpeg',
'-y', '-r', '%d' %(fps), # overwrite, 60fps
'-s', '%dx%d' % (initial_w, initial_h), # size of image string
'-pixel_format' , 'bgr24', # format
'-f', 'rawvideo', '-i', '-', # tell ffmpeg to expect raw video from the pipe
'http://localhost:8090/fac.ffm') # output encoding
p = subprocess.Popen(cmdstring, stdin=subprocess.PIPE)
while cap.isOpened():
flag, frame = cap.read()
if not flag:
break
key_pressed = cv2.waitKey(60)
# Start async inference
inf_start = time.time()
image = cv2.resize(frame, (w, h))
# Change data layout from HWC to CHW
image = image.transpose((2, 0, 1))
image = image.reshape((n, c, h, w))
# Start asynchronous inference for specified request.
infer_network.exec_net(cur_request_id, image)
# Wait for the result
if infer_network.wait(cur_request_id) == 0:
det_time = time.time() - inf_start
# Results of the output layer of the network
result = infer_network.get_output(cur_request_id)
if os.environ['PERF_COUNTS'] > str(0):
perf_count = infer_network.performance_counter(cur_request_id)
performance_counts(perf_count)
frame, current_count = ssd_parser(frame, result)
inf_time_message = "Inference time: {:.3f}ms" \
.format(det_time * 1000)
cv2.putText(frame, inf_time_message, (15, 15),
cv2.FONT_HERSHEY_COMPLEX, 0.5, (200, 10, 10), 1)
# When new person enters the video
if current_count > last_count:
start_time = time.time()
total_count = total_count + current_count - last_count
client.publish("person", json.dumps({"total": total_count}))
# Person duration in the video is calculated
if current_count < last_count:
duration = int(time.time() - start_time)
# Publish messages to the MQTT server
client.publish("person/duration",
json.dumps({"duration": duration}))
client.publish("person", json.dumps({"count": current_count}))
last_count = current_count
if key_pressed == 27:
break
p.stdin.write(frame.tostring())
if single_image_mode:
cv2.imwrite('output_image.jpg', frame)
infer_network.clean()
cap.release()
cv2.destroyAllWindows()
client.disconnect()
infer_network.clean()
if __name__ == '__main__':
main()
exit(0)