forked from isl-org/OpenBot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Detector.java
executable file
·333 lines (280 loc) · 9.43 KB
/
Detector.java
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
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
http://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.
==============================================================================*/
// Modified by Matthias Mueller - Intel Intelligent Systems Lab - 2020
package org.openbot.tflite;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.os.SystemClock;
import android.os.Trace;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.PriorityQueue;
import timber.log.Timber;
/**
* Wrapper for frozen detection models trained using the Tensorflow Object Detection API:
* github.com/tensorflow/models/tree/master/research/object_detection
*/
public abstract class Detector extends Network {
/** Labels corresponding to the output of the vision model. */
protected List<String> labels;
// Number of output detections
protected int NUM_DETECTIONS;
protected String modelPath;
protected int imageSizeX;
protected int imageSizeY;
/**
* Creates a detector with the provided configuration.
*
* @param activity The current Activity.
* @param model The model to use for classification.
* @param device The device to use for classification.
* @param numThreads The number of threads to use for classification.
* @return A detector with the desired configuration.
*/
public static Detector create(Activity activity, Model model, Device device, int numThreads)
throws IOException {
switch (model.classType) {
case MOBILENETV1_1_0_Q:
case MOBILENETV3_S_Q:
return new DetectorQuantizedMobileNet(activity, model, device, numThreads);
case YOLOV4:
return new DetectorFloatYoloV4(activity, model, device, numThreads);
default:
return null;
}
}
/** An immutable result returned by a Classifier/Detector describing what was recognized. */
public static class Recognition {
/**
* A unique identifier for what has been recognized. Specific to the class, not the instance of
* the object.
*/
private final String id;
/** Display name for the recognition. */
private final String title;
/**
* A sortable score for how good the recognition is relative to others. Higher should be better.
*/
private final Float confidence;
/** Location within the source image for the location of the recognized object. */
private RectF location;
/** Detected class of the recognized object. */
private int classId;
public Recognition(
final String id,
final String title,
final Float confidence,
final RectF location,
int classId) {
this.id = id;
this.title = title;
this.confidence = confidence;
this.location = location;
this.classId = classId;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public Float getConfidence() {
return confidence;
}
public RectF getLocation() {
return new RectF(location);
}
public void setLocation(RectF location) {
this.location = location;
}
public int getClassId() {
return classId;
}
@Override
public String toString() {
String resultString = "";
if (id != null) {
resultString += "[" + id + "] ";
}
if (title != null) {
resultString += title + " ";
}
if (confidence != null) {
resultString += String.format(Locale.US, "(%.1f%%) ", confidence * 100.0f);
}
if (location != null) {
resultString += location + " ";
}
return resultString.trim();
}
}
/** Initializes a {@code Detector}. */
protected Detector(Activity activity, Model model, Device device, int numThreads)
throws IOException {
super(activity, model, device, numThreads);
labels = loadLabelList(activity);
parseTflite();
Timber.d("Created a Tensorflow Lite Detector.");
}
/** Reads label list from Assets. */
private List<String> loadLabelList(Activity activity) throws IOException {
List<String> labels = new ArrayList<String>();
BufferedReader reader =
new BufferedReader(new InputStreamReader(activity.getAssets().open(getLabelPath())));
String line;
while ((line = reader.readLine()) != null) {
labels.add(line);
}
reader.close();
return labels;
}
public List<Recognition> recognizeImage(final Bitmap bitmap, String className)
throws IllegalArgumentException {
// Log this method so that it can be analyzed with systrace.
Trace.beginSection("recognizeImage");
Trace.beginSection("preprocessBitmap");
convertBitmapToByteBuffer(bitmap);
Trace.endSection(); // preprocessBitmap
// Copy the input data into TensorFlow.
Trace.beginSection("feed");
feedData();
Trace.endSection();
// Run the inference call.
Trace.beginSection("runInference");
long startTime = SystemClock.elapsedRealtime();
runInference();
long endTime = SystemClock.elapsedRealtime();
Trace.endSection();
Timber.v("Timecost to run model inference: %s", (endTime - startTime));
Trace.endSection(); // "recognizeImage"
return getRecognitions(className);
}
protected float mNmsThresh = 0.25f;
// non maximum suppression
protected ArrayList<Recognition> nms(ArrayList<Recognition> list) {
ArrayList<Recognition> nmsList = new ArrayList<Recognition>();
for (int k = 0; k < labels.size(); k++) {
// 1. Find max confidence per class
PriorityQueue<Recognition> pq =
new PriorityQueue<Recognition>(
50,
new Comparator<Recognition>() {
@Override
public int compare(final Recognition lhs, final Recognition rhs) {
// Intentionally reversed to put high confidence at the head of the queue.
return Float.compare(rhs.getConfidence(), lhs.getConfidence());
}
});
for (int i = 0; i < list.size(); ++i) {
if (list.get(i).getClassId() == k) {
pq.add(list.get(i));
}
}
// 2. Do non maximum suppression
while (pq.size() > 0) {
// insert detection with max confidence
Recognition[] a = new Recognition[pq.size()];
Recognition[] detections = pq.toArray(a);
Recognition max = detections[0];
nmsList.add(max);
pq.clear();
for (int j = 1; j < detections.length; j++) {
Recognition detection = detections[j];
RectF b = detection.getLocation();
if (box_iou(max.getLocation(), b) < mNmsThresh) {
pq.add(detection);
}
}
}
}
return nmsList;
}
protected float box_iou(RectF a, RectF b) {
return box_intersection(a, b) / box_union(a, b);
}
protected float box_intersection(RectF a, RectF b) {
float w =
overlap((a.left + a.right) / 2, a.right - a.left, (b.left + b.right) / 2, b.right - b.left);
float h =
overlap((a.top + a.bottom) / 2, a.bottom - a.top, (b.top + b.bottom) / 2, b.bottom - b.top);
if (w < 0 || h < 0) return 0;
float area = w * h;
return area;
}
protected float box_union(RectF a, RectF b) {
float i = box_intersection(a, b);
float u = (a.right - a.left) * (a.bottom - a.top) + (b.right - b.left) * (b.bottom - b.top) - i;
return u;
}
protected float overlap(float x1, float w1, float x2, float w2) {
float l1 = x1 - w1 / 2;
float l2 = x2 - w2 / 2;
float left = l1 > l2 ? l1 : l2;
float r1 = x1 + w1 / 2;
float r2 = x2 + w2 / 2;
float right = r1 < r2 ? r1 : r2;
return right - left;
}
/**
* Get the name of the label file stored in Assets.
*
* @return
*/
protected abstract String getLabelPath();
/**
* Run inference using the prepared input in {@link #imgData}. Afterwards, the result will be
* provided by getProbability().
*
* <p>This additional method is necessary, because we don't have a common base for different
* primitive data types.
*/
protected abstract void runInference();
/**
* Feeds the data
*
* <p>This additional method is necessary, because we can have different number of detections
*/
protected abstract void feedData();
/**
* Get the total number of labels.
*
* @return
*/
protected int getNumLabels() {
return labels.size();
}
public List<String> getLabels() {
List<String> list = new ArrayList<>();
for (String label : labels) if (!label.equals("???")) list.add(label);
return list;
}
/**
* Get the number of detections.
*
* @return
*/
protected abstract int getNumDetections();
/** Get specs from tflite file */
protected abstract void parseTflite();
/**
* Get the recognitions.
*
* @return
*/
protected abstract List<Recognition> getRecognitions(String className);
}