使用openCV图像运行推理

问题描述 投票:0回答:1

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

我跟着this的例子。

这是关于名为“imgData”的ByteBuffer变量的推断(第71行,类:org.tensorflow.lite.examples.classification.tflite.Classifier)

imgData看起来已经从同一个类(第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: https://stackoverflow.com/questions/13134682/convert-mat-to-bitmap-opencv-for-android
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。

android opencv tensorflow tensorflow-lite
1个回答
0
投票

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

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。

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

© www.soinside.com 2019 - 2024. All rights reserved.