首页 > 解决方案 > 为 TensorFlow Lite 模型从图像中获取 ByteBuffer

问题描述

我正在创建一个 android 应用程序以在执行实时人脸识别的 Google Glass Enterprise Edition 2 上运行。我使用 Camera X 作为我的 Camera API,使用 TensorFlow Lite (TFLite) 作为我的分类模型。但是,TFLite 模型输入需要 ByteBuffer,我无法从从 CameraX 检索到的图像转换成它。

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

Camera X 图像分析: 参考

            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, 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()

标签: javaandroidkotlintensorflow-litebytebuffer

解决方案


我已经取得了一些发现,并应用这些发现来帮助缩短我的问题。

  1. 我从 CameraX 获得的图像是 YUV 格式。我已经在 224X224 的 RGB 中训练了我的模型。为了适应我的问题,我首先将图像转换为 RGB 位图,然后将其裁剪为 224X224。之后将 Bitmap 转换为 ByteBuffer。

  2. 至于我的 TFLite 模型,TFLite 模型设法接受转换后的 RGB ByteBuffer 图像并对其进行处理。返回 TensorBuffer。


推荐阅读