![](/img/trans.png)
[英]TfLite Model is giving different output on Android app and in python . For most inputs tflite model gives same output on android . Why? Please fix
[英]Tflite model giving different output in Android (ml vision) and Python
我正在使用 ML Vision api 从 FaceNet model 创建嵌入,然后比较两个嵌入之间的余弦距离。 Android版本的output和Python相差很大。 Python 版本的性能优于 android 版本。 可能是什么问题? 我在两者中都使用 FaceNet model。
我正在使用 ML 套件来推断https://firebase.google.com/docs/ml-kit/android/use-custom-models
我认为这可能是由于 java 读取图像的方式引起的,因为 android 中制作的图像数组与 python 中相同图像的图像数组不同。
所以我被困在这个问题上,因为我正在关注ML vision docs上的谷歌文档,其中图像在将其提供给分类器之前被转换为浮点数组,它看起来像这样:
val bitmap = Bitmap.createScaledBitmap(yourInputImage, 224, 224, true)
val batchNum = 0
val input = Array(1) { Array(224) { Array(224) { FloatArray(3) } } }
for (x in 0..223) {
for (y in 0..223) {
val pixel = bitmap.getPixel(x, y)
// Normalize channel values to [-1.0, 1.0]. This requirement varies by
// model. For example, some models might require values to be normalized
// to the range [0.0, 1.0] instead.
input[batchNum][x][y][0] = (Color.red(pixel) - 127) / 255.0f
input[batchNum][x][y][1] = (Color.green(pixel) - 127) / 255.0f
input[batchNum][x][y][2] = (Color.blue(pixel) - 127) / 255.0f
}
}
然后我一步一步分析,发现获取像素的方式是错误的,与python的方式完全不同。
然后我从这个来源找到了这种方法,我用我的方式更改了 function:
private fun convertBitmapToByteBuffer(bitmap: Bitmap): ByteBuffer {
val imgData = ByteBuffer.allocateDirect(4 * INPUT_SIZE * INPUT_SIZE * PIXEL_SIZE)
imgData.order(ByteOrder.nativeOrder())
val intValues = IntArray(INPUT_SIZE * INPUT_SIZE)
imgData.rewind()
bitmap.getPixels(intValues, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
// Convert the image to floating point.
var pixel = 0
for (i in 0 until INPUT_SIZE) {
for (j in 0 until INPUT_SIZE) {
val `val` = intValues[pixel++]
imgData.putFloat(((`val`.shr(16) and 0xFF) - IMAGE_MEAN)/IMAGE_STD)
imgData.putFloat(((`val`.shr(8) and 0xFF)- IMAGE_MEAN)/ IMAGE_STD)
imgData.putFloat(((`val` and 0xFF) - IMAGE_MEAN)/IMAGE_STD)
}
}
return imgData;
}
它奏效了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.