1. create input
由于接收的是tensor,所以需要将图转化为tensor作为输入:
//将单通道转化为float数组
private float[] convertBitmapToByteBuffer(Bitmap bitmap) {
private int[] intValues = new int[IMAGE_WIDTH * IMAGE_HEIGHT];
int lengthValues = IMAGE_WIDTH * IMAGE_HEIGHT * 3;
float[] floatValues = new float[lengthValues];
FloatBuffer floatBuffer = FloatBuffer.wrap(floatValues, 0, lengthValues);
floatBuffer.rewind();
bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
// Convert the [grayScaled] image to floating point.
int pixel = 0;
for (int i = 0; i < getImageSizeX(); ++i) {
for (int j = 0; j < getImageSizeY(); ++j) {
final int val = intValues[pixel++];
floatBuffer.put(pixelValue & 0xFF);
floatBuffer.put((pixelValue >> 8) & 0xFF);
floatBuffer.put((pixelValue >> 16) & 0xFF);
}
}
return floatBuffer.toArray();
}
//RGB三通直接将BGR的数据传入生成 IMAGE_WIDTH * IMAGE_HEIGHT * 3的数组即可。
将图像数据转化为TensorFloat:
//传入输入层的Dimension
final FloatTensor tensor = mNeuralNetwork.createFloatTensor(1, 192, 192, 3);
//将以上图片数据写入tensor
tensor.write(input, 0, input.length);
//创建inputs
final Map<String, FloatTensor> inputs = new HashMap<>();
//传入Model的input Layer的名称(注意tensorFlow的模型需要加上输出的位置索引 DATA_INPUT_LAYER_NAME = "input:0")
inputs.put(DATA_INPUT_LAYER_NAME, tensor);
2. create output
指定模型的output Layer的名称:索引
//forward
final Map<String, FloatTensor> outputs = mNeuralNetwork.execute(inputs);
3. parse results
//该模型的输出层Dimension为 1*96 * 96 * 14
float resultOut[] = new float[96 * 96 * 14];
for (Map.Entry<String, FloatTensor> output : outputs.entrySet()) {
//OUTPUT_LAYER_NAME = "out_5_stage:0"
if (output.getKey().equals(OUTPUT_LAYER_NAME)) {
FloatTensor outputLayer = output.getValue();
outputLayer.read(resultOut, 0, 96 * 96 * 14, 0 );
}
}
此时结果就都在resultOut之中。