android - 无法在 UINT8 类型的 TensorFlowLite 张量和 Java 对象之间转换
问题描述
我正在使用 MLKiT 加载自定义 tensoflow 模型在读取模型时出现以下错误
java.lang.IllegalArgumentException:无法在 UINT8 类型的 TensorFlowLite 张量和 [[[[F 与 TensorFlowLite 类型 FLOAT32 兼容的 Java 对象之间进行转换。
我正在使用以下代码使用 tlflite 文件进行对象检测
private fun bitmapToInputArray(bitmap: Bitmap): Array<Array<Array<FloatArray>>> {
var bitmap = bitmap
bitmap = Bitmap.createScaledBitmap(bitmap, 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) / 128.0f
input[batchNum][x][y][1] = (Color.green(pixel) - 127) / 128.0f
input[batchNum][x][y][2] = (Color.blue(pixel) - 127) / 128.0f
}
}
return input
}
private fun setImageData(input: Array<Array<Array<FloatArray>>>) {
var inputs: FirebaseModelInputs? = null
try {
inputs = FirebaseModelInputs.Builder()
.add(input) // add() as many input arrays as your model requires
.build()
} catch (e: FirebaseMLException) {
e.printStackTrace()
}
firebaseInterpreter!!.run(inputs!!, inputOutputOptions!!)
.addOnSuccessListener(
OnSuccessListener<FirebaseModelOutputs> {
// ...
Log.d("Final",it.toString());
})
.addOnFailureListener(
object : OnFailureListener {
override fun onFailure(p0: Exception) {
// Task failed with an exception
// ..
}
})
}
解决方案
您的模型需要一个量化的图像。您可以这样准备:
val input = Array(1) { Array(224) { Array(224) { ByteArray(3) } } }
for (x in 0..223) {
for (y in 0..223) {
val pixel = bitmap.getPixel(x, y)
input[batchNum][x][y][0] = Color.red(pixel)
input[batchNum][x][y][1] = Color.green(pixel)
input[batchNum][x][y][2] = Color.blue(pixel)
}
}
请注意,将 ByteBuffer 传递给 tflite 通常比多维数组更容易。
推荐阅读
- r - 如何确定变量连续减少的第一行?
- go - bazel go_embed_data“无法嵌入”
- python - InvalidArgumentError: In[0] mismatch In[1] shape: 1 vs. 3: [22500,1] [3,1] 0 0 [Op:MatMul]
- javascript - Firestore collection.set 方法不起作用
- python - 使用 np 数组中的元组作为颜色时,cv2.rectangle 不起作用
- c++ - 我们能以某种方式使用 array[i] 而不是 *(array+i) 吗?
- r - dplyr:如何在创建新协变量的同时使用多个列进行 pivot_wider?
- angular - Ionic 5 和 Angular 12:canActivate 保护修改浏览器历史记录,即使从保护返回 false
- spring-boot - Asyn retry Junit默认没有运行3次
- python - RuntimeError: Timeout context manager 应该在任务内部使用,在异步函数之外发送 discord.py 消息