aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/lite/examples/android/app/src/main/java/org/tensorflow/demo/TFLiteObjectDetectionAPIModel.java
blob: bfb4a0a04bc90566736864bf62340d1032961858 (plain)
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
/* Copyright 2016 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.
==============================================================================*/

package org.tensorflow.demo;

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.os.Trace;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.Vector;
import org.tensorflow.demo.env.Logger;
import org.tensorflow.lite.Interpreter;

/**
 * Wrapper for frozen detection models trained using the Tensorflow Object Detection API:
 * github.com/tensorflow/models/tree/master/research/object_detection
 */
public class TFLiteObjectDetectionAPIModel implements Classifier {
  private static final Logger LOGGER = new Logger();

  // Only return this many results.
  private static final int NUM_RESULTS = 1917;
  private static final int NUM_CLASSES = 91;

  private static final float Y_SCALE = 10.0f;
  private static final float X_SCALE = 10.0f;
  private static final float H_SCALE = 5.0f;
  private static final float W_SCALE = 5.0f;

  // Config values.
  private int inputSize;

  private final float[][] boxPriors = new float[4][NUM_RESULTS];

  // Pre-allocated buffers.
  private Vector<String> labels = new Vector<String>();
  private int[] intValues;
  private float[][][] outputLocations;
  private float[][][] outputClasses;

  float[][][][] img;

  private Interpreter tfLite;

  private float expit(final float x) {
    return (float) (1. / (1. + Math.exp(-x)));
  }

  /** Memory-map the model file in Assets. */
  private static MappedByteBuffer loadModelFile(AssetManager assets, String modelFilename)
      throws IOException {
    AssetFileDescriptor fileDescriptor = assets.openFd(modelFilename);
    FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
    FileChannel fileChannel = inputStream.getChannel();
    long startOffset = fileDescriptor.getStartOffset();
    long declaredLength = fileDescriptor.getDeclaredLength();
    return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
  }

  private void loadCoderOptions(
      final AssetManager assetManager, final String locationFilename, final float[][] boxPriors)
      throws IOException {
    // Try to be intelligent about opening from assets or sdcard depending on prefix.
    final String assetPrefix = "file:///android_asset/";
    InputStream is;
    if (locationFilename.startsWith(assetPrefix)) {
      is = assetManager.open(locationFilename.split(assetPrefix, -1)[1]);
    } else {
      is = new FileInputStream(locationFilename);
    }

    final BufferedReader reader = new BufferedReader(new InputStreamReader(is));

    for (int lineNum = 0; lineNum < 4; ++lineNum) {
      String line = reader.readLine();
      final StringTokenizer st = new StringTokenizer(line, ", ");
      int priorIndex = 0;
      while (st.hasMoreTokens()) {
        final String token = st.nextToken();
        try {
          final float number = Float.parseFloat(token);
          boxPriors[lineNum][priorIndex++] = number;
        } catch (final NumberFormatException e) {
          // Silently ignore.
        }
      }
      if (priorIndex != NUM_RESULTS) {
        throw new RuntimeException(
            "BoxPrior length mismatch: " + priorIndex + " vs " + NUM_RESULTS);
      }
    }

    LOGGER.i("Loaded box priors!");
  }

  void decodeCenterSizeBoxes(float[][][] predictions) {
    for (int i = 0; i < NUM_RESULTS; ++i) {
      float ycenter = predictions[0][i][0] / Y_SCALE * boxPriors[2][i] + boxPriors[0][i];
      float xcenter = predictions[0][i][1] / X_SCALE * boxPriors[3][i] + boxPriors[1][i];
      float h = (float) Math.exp(predictions[0][i][2] / H_SCALE) * boxPriors[2][i];
      float w = (float) Math.exp(predictions[0][i][3] / W_SCALE) * boxPriors[3][i];

      float ymin = ycenter - h / 2.f;
      float xmin = xcenter - w / 2.f;
      float ymax = ycenter + h / 2.f;
      float xmax = xcenter + w / 2.f;

      predictions[0][i][0] = ymin;
      predictions[0][i][1] = xmin;
      predictions[0][i][2] = ymax;
      predictions[0][i][3] = xmax;
    }
  }

  /**
   * Initializes a native TensorFlow session for classifying images.
   *
   * @param assetManager The asset manager to be used to load assets.
   * @param modelFilename The filepath of the model GraphDef protocol buffer.
   * @param labelFilename The filepath of label file for classes.
   */
  public static Classifier create(
      final AssetManager assetManager,
      final String modelFilename,
      final String labelFilename,
      final int inputSize) throws IOException {
    final TFLiteObjectDetectionAPIModel d = new TFLiteObjectDetectionAPIModel();

    d.loadCoderOptions(assetManager, "file:///android_asset/box_priors.txt", d.boxPriors);

    InputStream labelsInput = null;
    String actualFilename = labelFilename.split("file:///android_asset/")[1];
    labelsInput = assetManager.open(actualFilename);
    BufferedReader br = null;
    br = new BufferedReader(new InputStreamReader(labelsInput));
    String line;
    while ((line = br.readLine()) != null) {
      LOGGER.w(line);
      d.labels.add(line);
    }
    br.close();

    d.inputSize = inputSize;

    try {
      d.tfLite = new Interpreter(loadModelFile(assetManager, modelFilename));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    // Pre-allocate buffers.
    d.img = new float[1][inputSize][inputSize][3];

    d.intValues = new int[d.inputSize * d.inputSize];
    d.outputLocations = new float[1][NUM_RESULTS][4];
    d.outputClasses = new float[1][NUM_RESULTS][NUM_CLASSES];
    return d;
  }

  private TFLiteObjectDetectionAPIModel() {}

  @Override
  public List<Recognition> recognizeImage(final Bitmap bitmap) {
    // Log this method so that it can be analyzed with systrace.
    Trace.beginSection("recognizeImage");

    Trace.beginSection("preprocessBitmap");
    // Preprocess the image data from 0-255 int to normalized float based
    // on the provided parameters.
    bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

    for (int i = 0; i < inputSize; ++i) {
      for (int j = 0; j < inputSize; ++j) {
        int pixel = intValues[j * inputSize + i];
        img[0][j][i][2] = (float) (pixel & 0xFF) / 128.0f - 1.0f;
        img[0][j][i][1] = (float) ((pixel >> 8) & 0xFF) / 128.0f - 1.0f;
        img[0][j][i][0] = (float) ((pixel >> 16) & 0xFF) / 128.0f - 1.0f;
      }
    }
    Trace.endSection(); // preprocessBitmap

    // Copy the input data into TensorFlow.
    Trace.beginSection("feed");
    outputLocations = new float[1][NUM_RESULTS][4];
    outputClasses = new float[1][NUM_RESULTS][NUM_CLASSES];

    Object[] inputArray = {img};
    Map<Integer, Object> outputMap = new HashMap<>();
    outputMap.put(0, outputLocations);
    outputMap.put(1, outputClasses);
    Trace.endSection();

    // Run the inference call.
    Trace.beginSection("run");
    tfLite.runForMultipleInputsOutputs(inputArray, outputMap);
    Trace.endSection();

    decodeCenterSizeBoxes(outputLocations);

    // Find the best detections.
    final PriorityQueue<Recognition> pq =
        new PriorityQueue<Recognition>(
            1,
            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());
              }
            });

    // Scale them back to the input size.
    for (int i = 0; i < NUM_RESULTS; ++i) {
      float topClassScore = -1000f;
      int topClassScoreIndex = -1;

      // Skip the first catch-all class.
      for (int j = 1; j < NUM_CLASSES; ++j) {
        float score = expit(outputClasses[0][i][j]);

        if (score > topClassScore) {
          topClassScoreIndex = j;
          topClassScore = score;
        }
      }

      if (topClassScore > 0.001f) {
        final RectF detection =
            new RectF(
                outputLocations[0][i][1] * inputSize,
                outputLocations[0][i][0] * inputSize,
                outputLocations[0][i][3] * inputSize,
                outputLocations[0][i][2] * inputSize);

        pq.add(
            new Recognition(
                "" + i,
                labels.get(topClassScoreIndex),
                outputClasses[0][i][topClassScoreIndex],
                detection));
      }
    }

    final ArrayList<Recognition> recognitions = new ArrayList<Recognition>();
    for (int i = 0; i < Math.min(pq.size(), 10); ++i) {
      Recognition recog = pq.poll();
      recognitions.add(recog);
    }
    Trace.endSection(); // "recognizeImage"
    return recognitions;
  }

  @Override
  public void enableStatLogging(final boolean logStats) {
  }

  @Override
  public String getStatString() {
    return "";
  }

  @Override
  public void close() {
  }
}