-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
221 lines (178 loc) · 7.11 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
"""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 logging as log
import paho.mqtt.client as mqtt
import numpy as np
from argparse import ArgumentParser
from inference import Network
# MQTT server environment variables
HOSTNAME = socket.gethostname()
IPADDRESS = socket.gethostbyname(HOSTNAME)
MQTT_HOST = IPADDRESS
MQTT_PORT = 3002
MQTT_KEEPALIVE_INTERVAL = 60
DEBUG = False
def build_argparser():
"""
Parse command line arguments.
:return: command line arguments
"""
parser = ArgumentParser()
parser.add_argument("-m", "--model", required=True, type=str,
help="Path to an xml file with a trained model.")
parser.add_argument("-i", "--input", required=True, type=str,
help="Path to image or video file")
parser.add_argument("-l", "--cpu_extension", required=False, type=str,
default=None,
help="MKLDNN (CPU)-targeted custom layers."
"Absolute path to a shared library with the"
"kernels impl.")
parser.add_argument("-d", "--device", type=str, default="CPU",
help="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)")
parser.add_argument("-pt", "--prob_threshold", type=float, default=0.5,
help="Probability threshold for detections filtering"
"(0.5 by default)")
return parser
def connect_mqtt():
client = mqtt.Client(transport="websockets")
client.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)
return client
def preprocess(frame, input_shape):
width, height = input_shape
output = np.copy(frame)
output = cv2.resize(output, (width, height))
output = output.transpose((2, 0, 1))
output = output[np.newaxis, :, :, :]
return output
def detect_persons(result, width, height, threshold):
boxes = list(filter(lambda conf: conf[2] > threshold, result[0][0]))
boxes = sorted(boxes, key=lambda x: x[2])
persons = []
for box in boxes:
image_id, label, conf, x_min, y_min, x_max, y_max = box
pt1 = (int(x_min * width), int(y_min * height))
pt2 = (int(x_max * width), int(y_max * height))
persons.append({ 'pt1': pt1, 'pt2': pt2 })
return persons
def draw_bounding_boxes(frame, persons):
for person in persons:
pt1 = person['pt1']
pt2 = person['pt2']
frame = cv2.rectangle(frame, pt1, pt2, (255, 0, 0), 1)
return frame
def show_inference_time(frame, time, frame_height):
performance = round(time * 1000, 2);
text = "Inference: {time} ms".format(time=performance)
frame = cv2.putText(img=frame,
text=text,
org=(30, frame_height - 30), # bottom left
fontFace=cv2.FONT_HERSHEY_DUPLEX, #COMPLEX_SMALL,
fontScale=0.5,
color=(139, 0, 0),
thickness=1);
return frame
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
"""
# Initialise the class
infer_network = Network()
# Set Probability threshold for detections
prob_threshold = args.prob_threshold
# Load the model through `infer_network`
infer_network.load_model(args.model, args.device)
_, _, height, width = infer_network.get_input_shape()
capture = cv2.VideoCapture(args.input)
capture.open(args.input)
frame_width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
frame_rate = int(capture.get(cv2.CAP_PROP_FPS))
if DEBUG:
output = cv2.VideoWriter('output.mp4',
cv2.VideoWriter_fourcc('M','J','P','G'),
24, # fps
frameSize=(width, height))
total_count = 0
samples = []
num_frames = 0
duration = 0
while capture.isOpened():
num_frames += 1
rc, frame = capture.read()
if not rc:
break
preprocessed_frame = preprocess(frame, (width, height))
start_time = time.time()
infer_network.exec_net(preprocessed_frame)
end_time = time.time()
status = infer_network.wait()
if status == 0:
frame = show_inference_time(frame, end_time - start_time, frame_height)
result = infer_network.get_output()
persons = detect_persons(result, frame_width, frame_height, prob_threshold)
frame = draw_bounding_boxes(frame, persons)
samples.append(len(persons))
if num_frames % frame_rate == 0:
mean = np.mean(samples)
count = np.ceil(mean)
total_count += count;
samples = []
duration += 1
if count == 0:
duration = 0
client.publish("person", json.dumps({ "count": count, "total": total_count }))
client.publish("person/duration", json.dumps({ "duration": duration }))
sys.stdout.buffer.write(frame)
sys.stdout.flush()
if DEBUG:
output.write(frame)
### TODO: Write an output image if `single_image_mode` ###
if DEBUG:
output.release()
client.disconnect()
capture.release()
cv2.destroyAllWindows()
def main():
"""
Load the network and parse the output.
:return: None
"""
# Grab command line args
args = build_argparser().parse_args()
# Connect to the MQTT server
client = connect_mqtt()
# Perform inference on the input stream
infer_on_stream(args, client)
if __name__ == '__main__':
main()