运行 使用 openCV 图像进行推理

Run inference with an openCV image

我有一个安装了 OpenCV4.0.1 和 TFLite 的 Android 项目。 我想用一个 cv::Mat 的预训练 MobileNetV2 进行推断,我从 CameraBridgeViewBase(Android 样式)中提取并裁剪了它。 但是有点难。

我遵循了 this 示例。

这会推断一个名为 "imgData" 的 ByteBuffer 变量(第 71 行,class:org.tensorflow.lite.examples.classification.tflite.Classifier)

imgData 看起来是在同一个 class(第 185 行)中调用 "convertBitmapToByteBuffer" 的方法中填充的,逐个像素地添加一个位图,看起来之前被裁剪得很少。

private int[] intValues = new int[224 * 224];
Mat _croppedFace = new Mat() // Cropped image from CvCameraViewFrame.rgba() method.

float[][] outputVal = new float[1][1]; // Output value from my MobileNetV2 // trained model (i've changed the output on training, tested on python)

// Following: 
Bitmap bitmap = Bitmap.createBitmap(_croppedFace.cols(), _croppedFace.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(_croppedFace, bitmap);

convertBitmapToByteBuffer(bitmap); // This call should be used as the example one.
// runInference();
_tflite.run(imgData, outputVal);

但是,看起来我的 NN 的 input_shape 不正确,但我正在关注 MobileNet 示例,因为我的 NN 是 MobileNetV2。

我已经解决了这个错误,但我确信这不是最好的方法。

Keras MobilenetV2 input_shape 是:(nBatches, 224, 224, nChannels)。 我只想预测单个图像,所以,nBaches == 1,我正在使用 RGB 模式,所以 nChannels == 3

// Nasty nasty, but works. nBatches == 2? -- _cropped.shape() == (244, 244), 3 channels.
float [][][][] _inputValue = new float[2][_cropped.cols()][_cropped.rows()][3];

// Fill the _inputValue
for(int i = 0; i < _croppedFace.cols(); ++i)
    for (int j = 0; j < _croppedFace.rows(); ++j)
        for(int z = 0; z < 3; ++z)
            _inputValue [0][i][j][z] = (float) _croppedFace.get(i, j)[z] / 255; // DL works better with 0:1 values.

/*
Output val, has this shape, but I don't  really know why.
I'm sure that one's of that 2's is for nClasses (I'm working with 2 classes)
But I don't really know why it's using the other one.
*/
 float[][] outputVal = new float[2][2];
// Tensorflow lite interpreter
_tflite.run(_inputValue , outputVal);

在 python 上具有相同的形状: Python预测: [[XXXXXX, YYYYY]] <- 当然,我制作的最后一层,这只是一个原型 NN。

希望有人得到帮助,也希望有人可以改进答案,因为这不是很优化。