Skip to content

Instantly share code, notes, and snippets.

@nodamu
Last active April 2, 2019 11:12
Show Gist options
  • Save nodamu/3dac072ae3336e14c59997c745cb60f8 to your computer and use it in GitHub Desktop.
Save nodamu/3dac072ae3336e14c59997c745cb60f8 to your computer and use it in GitHub Desktop.
This is where the classification happens. The image has to converted to bytebuffer before passing to the model
/** Writes Image data into a {@code ByteBuffer}. */
private void convertBitmapToByteBuffer(Bitmap bitmap) {
if (imgData == null) {
return;
}
imgData.rewind();
bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
// Convert the image to floating point.
int pixel = 0;
long startTime = SystemClock.uptimeMillis();
for (int i = 0; i < getImageSizeX(); ++i) {
for (int j = 0; j < getImageSizeY(); ++j) {
final int val = intValues[pixel++];
addPixelValue(val);
}
}
long endTime = SystemClock.uptimeMillis();
Log.d(TAG, "Timecost to put values into ByteBuffer: " + Long.toString(endTime - startTime));
}
void classifyFrame(Bitmap bitmap, SpannableStringBuilder builder) {
if (tflite == null) {
Log.e(TAG, "Image classifier has not been initialized; Skipped.");
builder.append(new SpannableString("Uninitialized Classifier."));
}
convertBitmapToByteBuffer(bitmap);
// Here's where the magic happens!!!
long startTime = SystemClock.uptimeMillis();
runInference();
long endTime = SystemClock.uptimeMillis();
Log.d(TAG, "Timecost to run model inference: " + Long.toString(endTime - startTime));
// Smooth the results across frames.
applyFilter();
// Print the results.
printTopKLabels(builder);
long duration = endTime - startTime;
SpannableString span = new SpannableString(duration + " ms");
span.setSpan(new ForegroundColorSpan(android.graphics.Color.LTGRAY), 0, span.length(), 0);
builder.append(span);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment