-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfcw.py
237 lines (208 loc) · 9.34 KB
/
fcw.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
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
A demo which runs object detection on camera frames using GStreamer.
It also provides support for Object Tracker.
Run default object detection:
python3 detect.py
Choose different camera and input encoding
python3 detect.py --videosrc /dev/video1 --videofmt jpeg
Choose an Object Tracker. Example : To run sort tracker
python3 detect.py --tracker sort
TEST_DATA=../all_models
Run coco model:
python3 detect.py \
--model ${TEST_DATA}/mobilenet_ssd_v2_coco_quant_postprocess_edgetpu.tflite \
--labels ${TEST_DATA}/coco_labels.txt
"""
import argparse
import collections
import common
import gstreamer
import numpy as np
import os
import re
import svgwrite
import time
from tracker import ObjectTracker
from periphery import GPIO
Object = collections.namedtuple('Object', ['id', 'score', 'bbox'])
def load_labels(path):
p = re.compile(r'\s*(\d+)(.+)')
with open(path, 'r', encoding='utf-8') as f:
lines = (p.match(line).groups() for line in f.readlines())
return {int(num): text.strip() for num, text in lines}
def shadow_text(dwg, x, y, text, font_size=20):
dwg.add(dwg.text(text, insert=(x+1, y+1), fill='black', font_size=font_size))
dwg.add(dwg.text(text, insert=(x, y), fill='white', font_size=font_size))
def generate_svg(src_size, inference_size, inference_box, objs, labels, text_lines, trdata, trackerFlag):
dwg = svgwrite.Drawing('', size=src_size)
src_w, src_h = src_size
inf_w, inf_h = inference_size
box_x, box_y, box_w, box_h = inference_box
scale_x, scale_y = src_w / box_w, src_h / box_h
for y, line in enumerate(text_lines, start=1):
shadow_text(dwg, 10, y*20, line)
if trackerFlag and (np.array(trdata)).size:
for td in trdata:
x0, y0, x1, y1, trackID = td[0].item(), td[1].item(
), td[2].item(), td[3].item(), td[4].item()
overlap = 0
for ob in objs:
dx0, dy0, dx1, dy1 = ob.bbox.xmin.item(), ob.bbox.ymin.item(
), ob.bbox.xmax.item(), ob.bbox.ymax.item()
area = (min(dx1, x1)-max(dx0, x0))*(min(dy1, y1)-max(dy0, y0))
if (area > overlap):
overlap = area
obj = ob
# Relative coordinates.
x, y, w, h = x0, y0, x1 - x0, y1 - y0
# Absolute coordinates, input tensor space.
x, y, w, h = int(x * inf_w), int(y *
inf_h), int(w * inf_w), int(h * inf_h)
# Subtract boxing offset.
x, y = x - box_x, y - box_y
# Scale to source coordinate space.
x, y, w, h = x * scale_x, y * scale_y, w * scale_x, h * scale_y
percent = int(100 * obj.score)
label = '{}% {} ID:{}'.format(
percent, labels.get(obj.id, obj.id), int(trackID))
shadow_text(dwg, x, y - 5, label)
dwg.add(dwg.rect(insert=(x, y), size=(w, h),
fill='none', stroke='red', stroke_width='2'))
else:
for obj in objs:
x0, y0, x1, y1 = list(obj.bbox)
# Relative coordinates.
x, y, w, h = x0, y0, x1 - x0, y1 - y0
# Absolute coordinates, input tensor space.
x, y, w, h = int(x * inf_w), int(y *
inf_h), int(w * inf_w), int(h * inf_h)
# Subtract boxing offset.
x, y = x - box_x, y - box_y
# Scale to source coordinate space.
x, y, w, h = x * scale_x, y * scale_y, w * scale_x, h * scale_y
percent = int(100 * obj.score)
label = '{}% {}'.format(percent, labels.get(obj.id, obj.id))
shadow_text(dwg, x, y - 5, label)
dwg.add(dwg.rect(insert=(x, y), size=(w, h),
fill='none', stroke='red', stroke_width='2'))
return dwg.tostring()
class BBox(collections.namedtuple('BBox', ['xmin', 'ymin', 'xmax', 'ymax'])):
"""Bounding box.
Represents a rectangle which sides are either vertical or horizontal, parallel
to the x or y axis.
"""
__slots__ = ()
def get_output(interpreter, score_threshold, top_k, image_scale=1.0):
"""Returns list of detected objects."""
boxes = common.output_tensor(interpreter, 0)
category_ids = common.output_tensor(interpreter, 1)
scores = common.output_tensor(interpreter, 2)
def make(i):
ymin, xmin, ymax, xmax = boxes[i]
return Object(
id=int(category_ids[i]),
score=scores[i],
bbox=BBox(xmin=np.maximum(0.0, xmin),
ymin=np.maximum(0.0, ymin),
xmax=np.minimum(1.0, xmax),
ymax=np.minimum(1.0, ymax)))
return [make(i) for i in range(top_k) if scores[i] >= score_threshold]
def main():
PIN_RLED = GPIO("/dev/gpiochip2", 9, "out")
PIN_BUZZ = GPIO("/dev/gpiochip4", 10, "out")
PIN_VIBR = GPIO("/dev/gpiochip4", 12, "out")
default_model_dir = '../models'
default_model = 'mobilenet_ssd_v2_coco_quant_postprocess_edgetpu.tflite'
default_labels = 'coco_labels.txt'
parser = argparse.ArgumentParser()
parser.add_argument('--model', help='.tflite model path',
default=os.path.join(default_model_dir, default_model))
parser.add_argument('--labels', help='label file path',
default=os.path.join(default_model_dir, default_labels))
parser.add_argument('--top_k', type=int, default=3,
help='number of categories with highest score to display')
parser.add_argument('--threshold', type=float, default=0.1,
help='classifier score threshold')
parser.add_argument('--videosrc', help='Which video source to use. ',
default='/dev/video0')
parser.add_argument('--videofmt', help='Input video format.',
default='raw',
choices=['raw', 'h264', 'jpeg'])
parser.add_argument('--tracker', help='Name of the Object Tracker To be used.',
default=None,
choices=[None, 'sort'])
args = parser.parse_args()
print('Loading {} with {} labels.'.format(args.model, args.labels))
interpreter = common.make_interpreter(args.model)
interpreter.allocate_tensors()
labels = load_labels(args.labels)
w, h, _ = common.input_image_size(interpreter)
inference_size = (w, h)
# Average fps over last 30 frames.
fps_counter = common.avg_fps_counter(30)
def user_callback(input_tensor, src_size, inference_box, mot_tracker):
nonlocal fps_counter
start_time = time.monotonic()
common.set_input(interpreter, input_tensor)
interpreter.invoke()
# For larger input image sizes, use the edgetpu.classification.engine for better performance
objs = get_output(interpreter, args.threshold, args.top_k)
end_time = time.monotonic()
detections = [] # np.array([])
for n in range(0, len(objs)):
element = [] # np.array([])
element.append(objs[n].bbox.xmin)
element.append(objs[n].bbox.ymin)
element.append(objs[n].bbox.xmax)
element.append(objs[n].bbox.ymax)
element.append(objs[n].score) # print('element= ',element)
detections.append(element) # print('dets: ',dets)
print("\nELEMENT:")
print(element)
print("OBJ ID:")
print(objs[n].id)
print("OBJ SCORE:")
print(objs[n].score)
print("\n")
if ((objs[n].id == 0) and (objs[n].score > 0.75)):
PIN_RLED.write(True)
PIN_BUZZ.write(True)
PIN_VIBR.write(True)
else:
PIN_RLED.write(False)
PIN_BUZZ.write(False)
PIN_VIBR.write(False)
# convert to numpy array # print('npdets: ',dets)
detections = np.array(detections)
trdata = []
trackerFlag = False
if detections.any():
if mot_tracker != None:
trdata = mot_tracker.update(detections)
trackerFlag = True
text_lines = [
'Inference: {:.2f} ms'.format((end_time - start_time) * 1000),
'FPS: {} fps'.format(round(next(fps_counter))), ]
if len(objs) != 0:
return generate_svg(src_size, inference_size, inference_box, objs, labels, text_lines, trdata, trackerFlag)
result = gstreamer.run_pipeline(user_callback,
src_size=(640, 480),
appsink_size=inference_size,
trackerName=args.tracker,
videosrc=args.videosrc,
videofmt=args.videofmt)
if __name__ == '__main__':
main()