TensorFlow系列:第五讲:移动端部署模型

embedded/2024/10/18 3:31:28/

项目地址:https://github.com/LionJackson/imageClassification
Flutter项目地址:https://github.com/LionJackson/flutter_image

一. 模型转换

编写tflite模型工具类:

python">import osimport PIL
import tensorflow as tf
import keras
import numpy as np
from PIL.Image import Image
from matplotlib import pyplot as pltfrom utils.dataset_loader import DatasetLoader
from utils.utils import Utils"""
tflite模型工具类
"""class TFLiteUtil:def __init__(self, saved_model_dir, path_url):self.save_model_dir = saved_model_dirself.path_url = path_url# 训练的模型生成标签列表def get_folder_names(self):folder_names = []for root, dirs, files in os.walk(self.path_url + '/train'):for dir_name in dirs:folder_names.append(dir_name)with open(self.save_model_dir + '.label', 'w') as file:for name in folder_names:file.write(name + '\n')return folder_names# 模型转成tflite格式def convert_tflite(self):self.get_folder_names()converter = tf.lite.TFLiteConverter.from_saved_model(self.save_model_dir)tflite_model = converter.convert()# 将转换后的 TFLite 模型保存为文件with open(self.save_model_dir + '.tflite', 'wb') as f:f.write(tflite_model)print("转换成功,已保存为 tflite")# 加载keras并转成tflitedef convert_model_tflite(self):self.get_folder_names()model = keras.models.load_model(self.save_model_dir + ".keras")converter = tf.lite.TFLiteConverter.from_keras_model(model)converter.optimizations = [tf.lite.Optimize.DEFAULT]converter.target_spec.supported_types = [tf.float16]tflite_model = converter.convert()# 将转换后的 TFLite 模型保存为文件with open(self.save_model_dir + '.tflite', 'wb') as f:f.write(tflite_model)print("转换成功(model),已保存为 tflite")# 批量识别 进行可视化显示def batch_evaluation(self, class_mode='categorical', image_size=(224, 224), num_images=25):dataset_loader = DatasetLoader(self.path_url, image_size=image_size, class_mode=class_mode)train_ds, val_ds, test_ds, class_names = dataset_loader.load_data()interpreter = tf.lite.Interpreter(self.save_model_dir + '.tflite')interpreter.allocate_tensors()# 获取输入和输出张量的信息input_details = interpreter.get_input_details()output_details = interpreter.get_output_details()plt.figure(figsize=(10, 10))for images, labels in test_ds.take(1):outputs = []for img in images:img_expanded = np.expand_dims(img, axis=0)interpreter.set_tensor(input_details[0]['index'], img_expanded)interpreter.invoke()output = interpreter.get_tensor(output_details[0]['index'])outputs.append(output)for i in range(num_images):plt.subplot(5, 5, i + 1)image = np.array(images[i]).astype("uint8")plt.imshow(image)index = int(np.argmax(outputs[i]))prediction = outputs[i][0][index]percentage_str = "{:.2f}%".format(prediction * 100)plt.title(f"{class_names[index]}: {percentage_str}")plt.axis("off")plt.subplots_adjust(hspace=0.5, wspace=0.5)plt.show()# 查看tflite模型信息def tflite_analyzer(self):# 加载 TFLite 模型interpreter = tf.lite.Interpreter(model_path=self.save_model_dir + '.tflite')interpreter.allocate_tensors()# 获取输入和输出的详细信息input_details = interpreter.get_input_details()output_details = interpreter.get_output_details()# 打印输入和输出的详细信息print("Input Details:")for detail in input_details:print(detail)print("\nOutput Details:")for detail in output_details:print(detail)# 列出所有使用的算子tensor_details = interpreter.get_tensor_details()print("\nTensor Details:")for tensor_detail in tensor_details:print("Index:", tensor_detail['index'])print("Name:", tensor_detail['name'])print("Shape:", tensor_detail['shape'])print("Shape Signature:", tensor_detail['shape_signature'])print("dtype:", tensor_detail['dtype'])print("Quantization:", tensor_detail['quantization'])print("Quantization Parameters:", tensor_detail['quantization_parameters'])print("Sparsity Parameters:", tensor_detail['sparsity_parameters'])print()

引用工具类:

python">if __name__ == '__main__':# train()# model_util = ModelUtil(SAVED_MODEL_DIR, PATH_URL)# model_util.batch_evaluation()tflite_util = TFLiteUtil(SAVED_MODEL_DIR, PATH_URL)tflite_util.convert_tflite()tflite_util.tflite_analyzer()tflite_util.batch_evaluation()

此时会生成tflite模型文件:

在这里插入图片描述

二. 使用模型

创建flutter项目,引入以下库:

  image: ^4.0.17path: ^1.8.3path_provider: ^2.0.15image_picker: ^0.8.8tflite_flutter: ^0.10.4camera: ^0.10.5+2

把模型文件拷贝到项目中:

在这里插入图片描述
核心代码:

import 'dart:developer';
import 'dart:io';
import 'dart:isolate';import 'package:camera/camera.dart';
import 'package:flutter/services.dart';
import 'package:image/image.dart';
import 'package:tflite_flutter/tflite_flutter.dart';import 'isolate_inference.dart';class ImageClassificationHelper {static const modelPath = 'assets/models/fruits.tflite';static const labelsPath = 'assets/models/fruits.label';late final Interpreter interpreter;late final List<String> labels;late final IsolateInference isolateInference;late Tensor inputTensor;late Tensor outputTensor;// Load modelFuture<void> _loadModel() async {final options = InterpreterOptions();// Use XNNPACK Delegateif (Platform.isAndroid) {options.addDelegate(XNNPackDelegate());}// Use GPU Delegate// doesn't work on emulator// if (Platform.isAndroid) {//   options.addDelegate(GpuDelegateV2());// }// Use Metal Delegateif (Platform.isIOS) {options.addDelegate(GpuDelegate());}// Load model from assetsinterpreter = await Interpreter.fromAsset(modelPath, options: options);// Get tensor input shape [1, 224, 224, 3]inputTensor = interpreter.getInputTensors().first;// Get tensor output shape [1, 1001]outputTensor = interpreter.getOutputTensors().first;log('Interpreter loaded successfully');}// Load labels from assetsFuture<void> _loadLabels() async {final labelTxt = await rootBundle.loadString(labelsPath);labels = labelTxt.split('\n');}Future<void> initHelper() async {_loadLabels();_loadModel();isolateInference = IsolateInference();await isolateInference.start();}Future<Map<String, double>> _inference(InferenceModel inferenceModel) async {ReceivePort responsePort = ReceivePort();isolateInference.sendPort.send(inferenceModel..responsePort = responsePort.sendPort);// get inference result.var results = await responsePort.first;return results;}// inference camera frameFuture<Map<String, double>> inferenceCameraFrame(CameraImage cameraImage) async {var isolateModel = InferenceModel(cameraImage, null, interpreter.address,labels, inputTensor.shape, outputTensor.shape);return _inference(isolateModel);}// inference still imageFuture<Map<String, double>> inferenceImage(Image image) async {var isolateModel = InferenceModel(null, image, interpreter.address, labels,inputTensor.shape, outputTensor.shape);return _inference(isolateModel);}Future<void> close() async {isolateInference.close();}
}

页面部分:

在这里插入图片描述


http://www.ppmy.cn/embedded/58789.html

相关文章

nx上darknet的使用-目标检测-在python中的使用

1 内置的代码 在darknet中已经内置了两个py文件 darknet_video.py与darknet_images.py用法类似&#xff0c;都是改一改给的参数就行了&#xff0c;我们说一下几个关键的参数 input 要预测哪张图像weights 要使用哪个权重config_file 要使用哪个cfg文件data_file 要使用哪个da…

【YashanDB知识库】yasql登录报错:YAS-00413

【问题分类】错误码处理 【关键字】yasql&#xff0c;00413 【问题描述】使用工具设置不同并发迁移数据的过程中&#xff0c;导致yasql登录报错&#xff1a;YAS-00413 【问题原因分析】工具使用与数据库使用资源超过了操作系统配置参数设置 【解决/规避方法】 ● 查看操作…

自动化数据集成的BI工具,为你提供决策洞察力

传统的商业智能&#xff08;BI&#xff09;报表系统采用的是“业务提报表需求&#xff0c;IT进行开发”的模式。决策管理者和业务人员提出用报表等来展示经营管理数据的需求&#xff1b;接着IT响应需求&#xff0c;进行需求沟通、数据处理加工、报表开发等主体工作&#xff1b;…

分布式系统—Ceph块存储系统(RBD接口)

目录 一、服务端操作 1 创建一个名为 rbd-xy101 的专门用于 RBD 的存储池 2 将存储池转换为 RBD 模式 3 初始化存储池 4 创建镜像 5 管理镜像 6.Linux客户端使用 在管理节点创建并授权一个用户可访问指定的 RBD 存储池 ​编辑修改RBD镜像特性&#xff0c;CentOS7默认情…

Spring Boot Vue 毕设系统讲解 3

目录 项目配置类 项目中配置的相关代码 spring Boot 拦截器相关知识 一、基于URL实现的拦截器&#xff1a; 二、基于注解的拦截器 三、把拦截器添加到配置中&#xff0c;相当于SpringMVC时的配置文件干的事儿&#xff1a; 项目配置类 项目中配置的相关代码 首先定义项目认…

优化 Java 数据结构选择与使用,提升程序性能与可维护性

优化 Java 数据结构选择与使用&#xff0c;提升程序性能与可维护性 引言 在软件开发中&#xff0c;数据结构的选择是影响程序性能、内存使用以及代码可维护性的关键因素之一。Java 作为一门广泛使用的编程语言&#xff0c;提供了丰富的内置数据结构&#xff0c;如数组、链表、…

自动驾驶决策和控制系统的研究

摘要 自动驾驶汽车的决策和控制系统是实现自主驾驶的核心部分。本文详细探讨了自动驾驶系统中决策和控制的基本原理、主要方法及其在实际应用中的挑战与前景。通过对路径规划、行为决策、运动控制等关键环节的分析&#xff0c;本文旨在为自动驾驶技术的发展提供理论基础和实践指…

【技术支持】npm镜像设置

临时设置 npm install <package> --registryhttps://registry.npmmirror.com/永久设置 npm config set registry https://registry.npmmirror.com/获取设置值 npm config get registry退回官方 npm config set registry https://registry.npmjs.org/