This repository has been archived by the owner on Jun 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdetect.py
171 lines (140 loc) · 5.2 KB
/
detect.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
# Lint as: python3
# 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.
"""Functions to work with detection models."""
import collections
import numpy as np
Object = collections.namedtuple("Object", ["id", "score", "bbox"])
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__ = ()
@property
def width(self):
"""Returns bounding box width."""
return self.xmax - self.xmin
@property
def height(self):
"""Returns bounding box height."""
return self.ymax - self.ymin
@property
def area(self):
"""Returns bound box area."""
return self.width * self.height
@property
def valid(self):
"""Returns whether bounding box is valid or not.
Valid bounding box has xmin <= xmax and ymin <= ymax which is equivalent to
width >= 0 and height >= 0.
"""
return self.width >= 0 and self.height >= 0
def scale(self, sx, sy):
"""Returns scaled bounding box."""
return BBox(
xmin=sx * self.xmin,
ymin=sy * self.ymin,
xmax=sx * self.xmax,
ymax=sy * self.ymax,
)
def translate(self, dx, dy):
"""Returns translated bounding box."""
return BBox(
xmin=dx + self.xmin,
ymin=dy + self.ymin,
xmax=dx + self.xmax,
ymax=dy + self.ymax,
)
def map(self, f):
"""Returns bounding box modified by applying f for each coordinate."""
return BBox(
xmin=f(self.xmin), ymin=f(self.ymin), xmax=f(self.xmax), ymax=f(self.ymax)
)
@staticmethod
def intersect(a, b):
"""Returns the intersection of two bounding boxes (may be invalid)."""
return BBox(
xmin=max(a.xmin, b.xmin),
ymin=max(a.ymin, b.ymin),
xmax=min(a.xmax, b.xmax),
ymax=min(a.ymax, b.ymax),
)
@staticmethod
def union(a, b):
"""Returns the union of two bounding boxes (always valid)."""
return BBox(
xmin=min(a.xmin, b.xmin),
ymin=min(a.ymin, b.ymin),
xmax=max(a.xmax, b.xmax),
ymax=max(a.ymax, b.ymax),
)
@staticmethod
def iou(a, b):
"""Returns intersection-over-union value."""
intersection = BBox.intersect(a, b)
if not intersection.valid:
return 0.0
area = intersection.area
return area / (a.area + b.area - area)
def input_size(interpreter):
"""Returns input image size as (width, height) tuple."""
_, height, width, _ = interpreter.get_input_details()[0]["shape"]
return width, height
def input_tensor(interpreter):
"""Returns input tensor view as numpy array of shape (height, width, 3)."""
tensor_index = interpreter.get_input_details()[0]["index"]
return interpreter.tensor(tensor_index)()[0]
def set_input(interpreter, size, resize):
"""Copies a resized and properly zero-padded image to the input tensor.
Args:
interpreter: Interpreter object.
size: original image size as (width, height) tuple.
resize: a function that takes a (width, height) tuple, and returns an RGB
image resized to those dimensions.
Returns:
Actual resize ratio, which should be passed to `get_output` function.
"""
width, height = input_size(interpreter)
w, h = size
scale = min(width / w, height / h)
w, h = int(w * scale), int(h * scale)
tensor = input_tensor(interpreter)
tensor.fill(0) # padding
_, _, channel = tensor.shape
tensor[:h, :w] = np.reshape(resize((w, h)), (h, w, channel))
return scale, scale
def output_tensor(interpreter, i):
"""Returns output tensor view."""
tensor = interpreter.tensor(interpreter.get_output_details()[i]["index"])()
return np.squeeze(tensor)
def get_output(interpreter, score_threshold, image_scale=(1.0, 1.0)):
"""Returns list of detected objects."""
boxes = output_tensor(interpreter, 0)
class_ids = output_tensor(interpreter, 1)
scores = output_tensor(interpreter, 2)
count = int(output_tensor(interpreter, 3))
width, height = input_size(interpreter)
image_scale_x, image_scale_y = image_scale
sx, sy = width / image_scale_x, height / image_scale_y
def make(i):
ymin, xmin, ymax, xmax = boxes[i]
return Object(
id=int(class_ids[i]),
score=float(scores[i]),
bbox=BBox(xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax)
.scale(sx, sy)
.map(int),
)
return [make(i) for i in range(count) if scores[i] >= score_threshold]