-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
236 lines (176 loc) · 7.6 KB
/
main.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
"""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 cv2
import json
import time
import logging as log
import paho.mqtt.client as mqtt
import argparse
from inference import Network
# MQTT server environment variables
HOSTNAME = socket.gethostname()
IPADDRESS = socket.gethostbyname(HOSTNAME)
MQTT_HOST = IPADDRESS
MQTT_PORT = 3001
MQTT_KEEPALIVE_INTERVAL = 120
def build_argparser():
parser = argparse.ArgumentParser("People Counter App")
m_desc = "Path to an xml file with a trained model."
i_desc = "Path to image or video file"
l_desc = "MKLDNN (CPU)-targeted custom layers. Absolute path to a shared library with the kernels impl."
d_desc = "Specify the target device to infer on: CPU, GPU, FPGA or MYRIAD is acceptable. Sample will look for a suitable plugin for device specified (CPU by default)"
pt_desc = "Probability threshold for detections filtering (0.5 by default)"
# -- Add required and optional groups
parser._action_groups.pop()
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
required.add_argument("-m", required=True, type=str,help=m_desc)
required.add_argument("-i", required=True, type=str, help=i_desc)
optional.add_argument("-l", required=False, type=str, default=None, help=l_desc)
optional.add_argument("-d", type=str, default="CPU", help=d_desc)
optional.add_argument("-pt", type=float, default=0.5, help=pt_desc)
args = parser.parse_args()
return args
def connect_mqtt():
### TODO: Connect to the MQTT client ###
client = mqtt.Client()
client.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)
return client
def draw_boxes(frame, result,probability,color, width, height):
count = 0
for box in result[0][0]:
conf = box[2]
output_class = box[1]
if conf>=probability and output_class==1 : #output_class = 1 is for person, as per coco.names file
xmin = int(box[3] * width)
ymin = int(box[4] * height)
xmax = int(box[5] * width)
ymax = int(box[6] * height)
cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), color, 1)
count = count+1
return frame,count
def infer_on_stream(args, client):
"""
Initialize the inference network, stream video to network,
and output stats and video.
:param args: Command line arguments parsed by `build_argparser()`
:param client: MQTT client
:return: None
"""
# Initializing Variables
global width,height,prob_threshold
image_mode = False
last_count = 0
total_count = 0
start_time = 0
last_last_count = 0
# Initialise the class
infer_network = Network()
# Set Probability threshold for detections
prob_threshold = args.pt
### TODO: Load the model through `infer_network` ###
infer_network.load_model(args.m, args.d, args.l)
net_input_shape = infer_network.get_input_shape()
### TODO: Handle the input stream ###
# Checking Image File
if args.i.endswith('.jpg') or args.i.endswith('.png'):
image_mode = True
Input_stream = args.i
# Checking for input video from the camera
elif args.i == 'CAM':
Input_stream = 0
# Checking for Video File
else:
Input_stream = args.i
cap = cv2.VideoCapture(Input_stream)
if Input_stream:
cap.open(args.i)
if not cap.isOpened():
log.error("ERROR! Unable to open the media")
width = int(cap.get(3))
height = int(cap.get(4))
### TODO: Loop until stream is over ###
while cap.isOpened():
### TODO: Read from the video capture ###
flag,frame = cap.read()
if not flag:
break
inf_start = time.time()
key_pressed = cv2.waitKey(60)
### TODO: Pre-process the image as needed ###
p_frame = cv2.resize(frame, (net_input_shape[3], net_input_shape[2]))
p_frame = p_frame.transpose((2,0,1))
p_frame = p_frame.reshape(1, *p_frame.shape)
### TODO: Start asynchronous inference for specified request ###
infer_network.exec_net(p_frame)
### TODO: Wait for the result ###
status = infer_network.wait()
if status==0:
det_time = time.time() - inf_start
### TODO: Get the results of the inference request ###
### TODO: Extract any desired stats from the results ###
result = infer_network.get_output()
frame,current_count = draw_boxes(frame, result,prob_threshold,(0,0,255), width, height)
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)
### TODO: Calculate and send relevant information on ###
### current_count, total_count and duration to the MQTT server ###
### Topic "person": keys of "count" and "total" ###
### Topic "person/duration": key of "duration" ###
if current_count > last_count:
start_time = time.time()
if current_count < last_count: #To avoid False Negatives
if(last_last_count>=last_count):
duration = int(time.time() - start_time)
total_count = total_count + last_count - current_count
client.publish("person", json.dumps({"total": total_count}))
client.publish("person/duration",json.dumps({"duration": duration}))
client.publish("person", json.dumps({"count": current_count}))
last_last_count = last_count
last_count = current_count
if key_pressed==27:
break
### TODO: Send the frame to the FFMPEG server ###
sys.stdout.buffer.write(frame)
sys.stdout.flush()
if image_mode:
cv2.imwrite('output_image.jpg', frame)
### TODO: Write an output image if `single_image_mode` ###
cap.release()
cv2.destroyAllWindows()
client.disconnect()
def main():
"""
Load the network and parse the output.
:return: None
"""
# Grab command line args
args = build_argparser()
# Connect to the MQTT server
client = connect_mqtt()
# Perform inference on the input stream
infer_on_stream(args, client)
if __name__ == '__main__':
main()