aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/examples/android/src/org/tensorflow/demo/TensorFlowMultiBoxDetector.java
blob: 34a43616265180f7f85b8e661236441ad24a524d (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
/* 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.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.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import org.tensorflow.contrib.android.TensorFlowInferenceInterface;
import org.tensorflow.demo.env.Logger;

/**
 * A detector for general purpose object detection as described in Scalable Object Detection using
 * Deep Neural Networks (https://arxiv.org/abs/1312.2249).
 */
public class TensorFlowMultiBoxDetector implements Classifier {
  private static final Logger LOGGER = new Logger();

  static {
    System.loadLibrary("tensorflow_demo");
  }

  // Only return this many results with at least this confidence.
  private static final int MAX_RESULTS = Integer.MAX_VALUE;

  // Config values.
  private String inputName;
  private int inputSize;
  private int imageMean;
  private float imageStd;

  // Pre-allocated buffers.
  private int[] intValues;
  private float[] floatValues;
  private float[] outputLocations;
  private float[] outputScores;
  private String[] outputNames;
  private int numLocations;

  private TensorFlowInferenceInterface inferenceInterface;

  private float[] boxPriors;

  /**
   * 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 locationFilename The filepath of label file for classes.
   * @param inputSize The input size. A square image of inputSize x inputSize is assumed.
   * @param imageMean The assumed mean of the image values.
   * @param imageStd The assumed std of the image values.
   * @param inputName The label of the image input node.
   * @param outputName The label of the output node.
   */
  public static Classifier create(
      final AssetManager assetManager,
      final String modelFilename,
      final String locationFilename,
      final int numLocations,
      final int inputSize,
      final int imageMean,
      final float imageStd,
      final String inputName,
      final String outputName) {
    final TensorFlowMultiBoxDetector d = new TensorFlowMultiBoxDetector();
    d.inputName = inputName;
    d.inputSize = inputSize;
    d.imageMean = imageMean;
    d.imageStd = imageStd;
    d.numLocations = numLocations;

    d.boxPriors = new float[numLocations * 8];

    try {
      d.loadCoderOptions(assetManager, locationFilename, d.boxPriors);
    } catch (final IOException e) {
      throw new RuntimeException("Error initializing box priors from " + locationFilename);
    }

    // Pre-allocate buffers.
    d.outputNames = outputName.split(",");
    d.intValues = new int[inputSize * inputSize];
    d.floatValues = new float[inputSize * inputSize * 3];
    d.outputScores = new float[numLocations];
    d.outputLocations = new float[numLocations * 4];

    d.inferenceInterface = new TensorFlowInferenceInterface();

    final int status = d.inferenceInterface.initializeTensorFlow(assetManager, modelFilename);
    if (status != 0) {
      LOGGER.e("TF init status: " + status);
      throw new RuntimeException("TF init status (" + status + ") != 0");
    }
    return d;
  }

  private TensorFlowMultiBoxDetector() {}

  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]);
    } else {
      is = new FileInputStream(locationFilename);
    }

    // Read values. Number of values per line doesn't matter, as long as they are separated
    // by commas and/or whitespace, and there are exactly numLocations * 8 values total.
    // Values are in the order mean, std for each consecutive corner of each box, for a total of 8
    // per location.
    final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    int priorIndex = 0;
    String line;
    while ((line = reader.readLine()) != null) {
      final StringTokenizer st = new StringTokenizer(line, ", ");
      while (st.hasMoreTokens()) {
        final String token = st.nextToken();
        try {
          final float number = Float.parseFloat(token);
          boxPriors[priorIndex++] = number;
        } catch (final NumberFormatException e) {
          // Silently ignore.
        }
      }
    }
    if (priorIndex != boxPriors.length) {
      throw new RuntimeException(
          "BoxPrior length mismatch: " + priorIndex + " vs " + boxPriors.length);
    }
  }

  private float[] decodeLocationsEncoding(final float[] locationEncoding) {
    final float[] locations = new float[locationEncoding.length];
    boolean nonZero = false;
    for (int i = 0; i < numLocations; ++i) {
      for (int j = 0; j < 4; ++j) {
        final float currEncoding = locationEncoding[4 * i + j];
        nonZero = nonZero || currEncoding != 0.0f;

        final float mean = boxPriors[i * 8 + j * 2];
        final float stdDev = boxPriors[i * 8 + j * 2 + 1];
        float currentLocation = currEncoding * stdDev + mean;
        currentLocation = Math.max(currentLocation, 0.0f);
        currentLocation = Math.min(currentLocation, 1.0f);
        locations[4 * i + j] = currentLocation;
      }
    }

    if (!nonZero) {
      LOGGER.w("No non-zero encodings; check log for inference errors.");
    }
    return locations;
  }

  private float[] decodeScoresEncoding(final float[] scoresEncoding) {
    final float[] scores = new float[scoresEncoding.length];
    for (int i = 0; i < scoresEncoding.length; ++i) {
      scores[i] = 1 / ((float) (1 + Math.exp(-scoresEncoding[i])));
    }
    return scores;
  }

  @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 < intValues.length; ++i) {
      floatValues[i * 3 + 0] = ((intValues[i] & 0xFF) - imageMean) / imageStd;
      floatValues[i * 3 + 1] = (((intValues[i] >> 8) & 0xFF) - imageMean) / imageStd;
      floatValues[i * 3 + 2] = (((intValues[i] >> 16) & 0xFF) - imageMean) / imageStd;
    }
    Trace.endSection(); // preprocessBitmap

    // Copy the input data into TensorFlow.
    Trace.beginSection("fillNodeFloat");
    inferenceInterface.fillNodeFloat(
        inputName, new int[] {1, inputSize, inputSize, 3}, floatValues);
    Trace.endSection();

    // Run the inference call.
    Trace.beginSection("runInference");
    inferenceInterface.runInference(outputNames);
    Trace.endSection();

    // Copy the output Tensor back into the output array.
    Trace.beginSection("readNodeFloat");
    final float[] outputScoresEncoding = new float[numLocations];
    final float[] outputLocationsEncoding = new float[numLocations * 4];
    inferenceInterface.readNodeFloat(outputNames[0], outputLocationsEncoding);
    inferenceInterface.readNodeFloat(outputNames[1], outputScoresEncoding);
    Trace.endSection();

    outputLocations = decodeLocationsEncoding(outputLocationsEncoding);
    outputScores = decodeScoresEncoding(outputScoresEncoding);

    // 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 < outputScores.length; ++i) {
      final RectF detection =
          new RectF(
              outputLocations[4 * i] * inputSize,
              outputLocations[4 * i + 1] * inputSize,
              outputLocations[4 * i + 2] * inputSize,
              outputLocations[4 * i + 3] * inputSize);
      pq.add(new Recognition("" + i, null, outputScores[i], detection));
    }

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

  @Override
  public void enableStatLogging(final boolean debug) {
    inferenceInterface.enableStatLogging(debug);
  }

  @Override
  public String getStatString() {
    return inferenceInterface.getStatString();
  }

  @Override
  public void close() {
    inferenceInterface.close();
  }
}