从 TensorFlow Lite 模型的图像中获取 ByteBuffer

问题描述

我正在创建一个在谷歌眼镜企业版 2 上运行的 android 应用程序,它可以进行实时人脸识别。我使用 Camera X 作为我的相机 API,使用 TensorFlow Lite (TFLite) 作为我的分类模型。但是,TFLite 模型输入需要 ByteBuffer,我无法将其从从 CameraX 检索到的图像转换。

如何将我的图像从 CameraX 获取到我的 TFLite 模型的 ByteBuffer 类中?

相机 X 图像分析: Reference

            val imageAnalysis = ImageAnalysis.Builder()
                    .setTargetResolution(Size(640,360))
                    .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                    .build()

            imageAnalysis.setAnalyzer(AsyncTask.THREAD_POOL_EXECUTOR,ImageAnalysis.Analyzer { imageProxy ->
                val rotationDegrees = imageProxy.imageInfo.rotationDegrees
                val mediaImage = imageProxy.image

                if (mediaImage != null) {
                    val image = InputImage.fromMediaImage(mediaImage,rotationDegrees)

                    /* Classify the Image using TensorFlow Lite Model */

                }

            })

TensorFlow 模型示例代码

val model = FaceRecognitionModel.newInstance(context)

// Creates inputs for reference.
val inputFeature0 = TensorBuffer.createFixedSize(intArrayOf(1,224,3),DataType.FLOAT32)
inputFeature0.loadBuffer(byteBuffer)

// Runs model inference and gets result.
val outputs = model.process(inputFeature0)
val outputFeature0 = outputs.outputFeature0AsTensorBuffer

// Releases model resources if no longer used.
model.close()

解决方法

尝试使用 TensorImage class 中的 TensorFlow Lite Support Library

大致上,您可以按照以下步骤操作。

  1. Image 对象转换为 Bitmap。应该还有其他关于如何执行此操作的 Stackoverflow 问题(例如,this answer
  2. 使用 TensorImage 工厂从 Bitmap 对象创建一个 TensorImage.fromBitmap() 对象。
  3. getBuffer() 对象调用 TensorImage 方法以获取底层 ByteBuffer

您可能还需要进行一些图像预处理,以防来自 CameraX 的图像与模型预期的格式不完全匹配。为此,您可以探索ImageProcessor utility

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...