【Tflite模型】yolov5 tflite模型推理

#1.导入python库
#使用tflite_runtime来替换tensorflow,减少每次检测加载tf的时间
import cv2
import numpy as np
import tflite_runtime.interpreter as tflite
#import tensorflow as tf
#2.加载TFLite模型,具体模型文件根据模型的网络结构为主,解码不唯一,这个其中一种方法
interpreter = tflite.Interpreter(model_path=“detect.tflite”)
interpreter.allocate_tensors()
#3.获取模型输入、输出的数据的信息
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

#4.输入检测图像,处理图像矩阵(重点)
frame = cv2.imread("img/1.jpg")
#原图尺寸
imH, imW, _ = np.shape(frame)
#模型图尺寸
input_shape = input_details[0]['shape']
# RGB转BGR
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 设置输入尺寸
frame_resized = cv2.resize(frame_rgb, (input_shape[1], input_shape[2]))
# 添加一维度
img = np.expand_dims(frame_resized, axis=0)
# float32浮点数,看模型量化类型unit8,不需要转换
#input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], img)

#5.创建检测网络层
interpreter.invoke()
#6.检测框/类别/置信度的检测
boxes = interpreter.get_tensor(output_details[0]['index'])[0]  
classes = interpreter.get_tensor(output_details[1]['index'])[0]  
scores = interpreter.get_tensor(output_details[2]['index'])[0]
#7.绘画检测框
# 对于概率大于 50%的进行显示
for i in range(len(scores)):
    if ((scores[i] > 0.35) and (scores[i] <= 1.0)):
        # 获取边框坐标
        ymin = int(max(1, (boxes[i][0] * imH)))
        xmin = int(max(1, (boxes[i][1] * imW)))
        ymax = int(min(imH, (boxes[i][2] * imH)))
        xmax = int(min(imW, (boxes[i][3] * imW)))
        # 画框
        cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), (10, 255, 0), 2)
        # 获取检测标签
        object_name = str(int(classes[i]))  
        label = '%s 0.%d' % (object_name, int(scores[i] * 100))  
        print("label", label)
        # 显示标记
        frame = paint_chinese_opencv(frame, label, (xmin, ymin), (255, 0, 0))
cv2.imshow('object detect', img)
cv2.waitKey(0)
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值