将Keras模型转为TensorFlow Lite在Kivy安卓应用运行遇错求助
我尝试将Keras模型转换为TensorFlow Lite格式,在Kivy开发的安卓应用中使用,但应用启动时出现加载错误。
模型代码
model_v3 = tf.keras.applications.MobileNet( weights='imagenet', include_top=False, input_shape=(224, 224, 3) ) for layer in model_v3.layers[:]: layer.trainable = True model = tf.keras.Sequential() for layer in model_v3.layers: model.add(layer) model.add(layers.Flatten()) model.add(layers.Dense(256, activation='relu')) model.add(layers.Dropout(0.3)) model.add(layers.Dense(128, activation='relu')) model.add(layers.Dropout(0.5)) model.add(layers.Dense(8, activation='softmax')) model.summary()
TFLite转换代码
model.save('model.keras') model = keras.models.load_model('/content/model.keras') converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert() with open('mobilenet_224.tflite', 'wb') as f: f.write(tflite_model)
应用启动错误日志
11-12 10:12:50.932 6678 10552 I python : File "jnius/jnius_export_class.pxi", line 269, in jnius.jnius.JavaClass.init
11-12 10:12:50.933 6678 10552 I python : File "jnius/jnius_export_class.pxi", line 383, in jnius.jnius.JavaClass.call_constructor
11-12 10:12:50.933 6678 10552 I python : File "jnius/jnius_utils.pxi", line 79, in jnius.jnius.check_exception
11-12 10:12:50.934 6678 10552 I python : jnius.jnius.JavaException: JVM exception occurred: Contents of /mobilenet_224.tflite does not encode a valid TensorFlow Lite
model: Could not open '/mobilenet_224.tflite'.
11-12 10:12:50.934 6678 10552 I python : The model allocation is null/empty java.lang.IllegalArgumentException
11-12 10:12:50.934 6678 10552 I python : Python for android ended.
环境配置
- 参考第三方Kivy应用的模型加载逻辑实现
- buildozer.spec依赖配置:
android.gradle_dependencies = org.tensorflow:tensorflow-lite:+,org.tensorflow:tensorflow-lite-support:+,org.tensorflow:tensorflow-lite-gpu:+
解决方案及原因分析
核心原因
错误提示Could not open '/mobilenet_224.tflite',说明安卓应用无法找到指定路径的模型文件,主要有两个触发点:
- 模型文件未被正确打包进APK安装包
- 加载模型时使用了安卓系统无法直接访问的绝对路径
修复步骤
确保模型被正确打包
在buildozer.spec中添加模型文件到资源打包配置项,示例:android.add_assets = mobilenet_224.tflite注意将
tflite文件放在项目根目录,若模型在子目录中,需填写相对路径(如assets/models/mobilenet_224.tflite)。使用安卓兼容的路径加载模型
安卓设备的assets目录文件无法通过绝对路径直接读取,需通过AssetManager读取文件内容后加载,示例代码:from kivy.utils import platform import os import tensorflow as tf def load_tflite_model(): if platform == 'android': from android import mActivity asset_manager = mActivity.getAssets() # 读取模型二进制内容 with asset_manager.open('mobilenet_224.tflite', 'rb') as f: model_content = f.read() interpreter = tf.lite.Interpreter(model_content=model_content) else: # 桌面环境使用本地路径加载 model_path = os.path.join(os.path.dirname(__file__), 'mobilenet_224.tflite') interpreter = tf.lite.Interpreter(model_path=model_path) interpreter.allocate_tensors() return interpreter验证模型文件有效性
在本地环境测试模型是否可正常加载,排除转换过程中的问题:import tensorflow as tf interpreter = tf.lite.Interpreter(model_path='mobilenet_224.tflite') interpreter.allocate_tensors() print("模型加载成功")固定TFLite依赖版本
避免使用+自动匹配版本导致的兼容性问题,建议指定具体版本:android.gradle_dependencies = org.tensorflow:tensorflow-lite:2.15.0,org.tensorflow:tensorflow-lite-support:0.4.4,org.tensorflow:tensorflow-lite-gpu:2.15.0
内容的提问来源于stack exchange,提问作者Vishak Raj

