#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)
11-05
3150

06-18
1481
