python中使用tflite推理网络

  • 1、使用tensorflow库
  • 2、使用tflite_runtime库
    • 2.1 安装tflite_runtime库
    • 2.2 推理

如果我们得到了tflite文件,如何在python中使用?这里可以在tensorflow库的帮助下或者tflite_runtime库的帮助下使用

1、使用tensorflow库

tensorflow库中有个lite子库,是为tflite而设计的
给出示例代码:

import tensorflow as tf
import cv2
import numpy as np


def preprocess(image):	# 输入图像预处理
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image = cv2.resize(image, (64, 64))
    tensor = np.expand_dims(image, axis=[0, -1])
    tensor = tensor.astype('float32')
    return tensor


# API文档:https://www.tensorflow.org/api_docs/python/tf/lite/Interpreter#args_1

emotion_model_tflite = tf.lite.Interpreter("output.tflite")	# 加载tflite模型

emotion_model_tflite.allocate_tensors()  # 预先计划张量分配以优化推理
tflife_input_details = emotion_model_tflite.get_input_details()  # 获取输入节点的细节
tflife_output_details = emotion_model_tflite.get_output_details()  # 获取输出节点的细节

# 加载并处理成输入张量,和keras推理或者tensorflow推理的输入张量一样
img = cv2.imread("1fae49da5f2472cf260e3d0aa08d7e32.jpeg")
input_tensor = preprocess(img)

# 填入输入tensor
emotion_model_tflite.set_tensor(tflife_input_details[0]['index'], input_tensor)
# 运行推理
emotion_model_tflite.invoke()
# 获取推理结果
custom = emotion_model_tflite.get_tensor(tflife_output_details[0]['index'])

print(custom)

2、使用tflite_runtime库

见名知意,tflite_runtime就是tflite的运行环境库。因为tensorflow毕竟太大了,如果我们只是想使用tflite模型推理,那么使用该库是个不错的选择

2.1 安装tflite_runtime库

首先在安装 TensorFlow Lite 解释器根据你的平台和python版本,下载对应的whl文件,然后使用pip安装即可:pip install 下载的whl文件路径
在这里插入图片描述

2.2 推理

先给出代码:

import tflite_runtime.interpreter as tflite	# 改动一
import cv2
import numpy as np


def preprocess(image):
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image = cv2.resize(image, (64, 64))
    tensor = np.expand_dims(image, axis=[0, -1])
    tensor = tensor.astype('float32')
    return tensor




emotion_model_tflite = tflite.Interpreter("output.tflite")	# 改动二

emotion_model_tflite.allocate_tensors() 
tflife_input_details = emotion_model_tflite.get_input_details()
tflife_output_details = emotion_model_tflite.get_output_details()

img = cv2.imread("1fae49da5f2472cf260e3d0aa08d7e32.jpeg")
input_tensor = preprocess(img)


emotion_model_tflite.set_tensor(tflife_input_details[0]['index'], input_tensor)

emotion_model_tflite.invoke()

custom = emotion_model_tflite.get_tensor(tflife_output_details[0]['index'])

print(custom)

你可能感兴趣的:(TensorFlowLite,python,tensorflow,深度学习)