1硬件环境:树莓派4b+和官方

2 操作系统 2020-05-27-2020-05-27-raspios-buster-full-armhf(官方版本

3安装tflite:Python 快速入门  |  TensorFlow Lite

https://blog.csdn.net/zhqh100/article/details/103361480  参考网址
pip3 install tflite_runtime-2.1.0.post1-cp37-cp37m-linux_x86_64.whl

4安装opencv 我这里早就安装过OpenCv

5下载model

参考https://www.tensorflow.org/lite/examples/object_detection/overview

https://storage.googleapis.com/download.tensorflow.org/models/tflite/coco_ssd_mobilenet_v1_1.0_quant_2018_06_29.zip
 

6. python3 执行如下代码:

# 转载网址https://blog.csdn.net/zhqh100/article/details/103361480
# 使用的板子是树莓派3b
import tflite_runtime.interpreter as tflite
 
import cv2
import numpy as np
 
with open("/home/pi/dection/labelmap.txt", 'r') as f:
    lines = f.readlines()
labels = []
for line in lines:
    labels.append(line.strip())
 
font = cv2.FONT_HERSHEY_SIMPLEX
 
interpreter = tflite.Interpreter("/home/pi/dection/detect.tflite")
interpreter.allocate_tensors()
 
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]
floating_model = False
if input_details[0]['dtype'] == np.float32:
    floating_model = True
 
cap = cv2.VideoCapture(0)
 
while True:
    ret, picture = cap.read()
 
    initial_h, initial_w, channels = picture.shape
    frame = cv2.resize(picture, (width, height))
 
    # add N dim
    input_data = np.expand_dims(frame, axis=0)
 
    if floating_model:
        input_data = (np.float32(input_data) - 127.5) / 127.5
 
    # interpreter.set_num_threads(4)
    interpreter.set_tensor(input_details[0]['index'], input_data)
 
    interpreter.invoke()
 
    detected_boxes = interpreter.get_tensor(output_details[0]['index'])
    detected_classes = interpreter.get_tensor(output_details[1]['index'])
    detected_scores = interpreter.get_tensor(output_details[2]['index'])
    num_boxes = interpreter.get_tensor(output_details[3]['index'])
 
    for i in range(int(num_boxes)):
        top, left, bottom, right = detected_boxes[0][i]
        score = detected_scores[0][i]
        if score > 0.5:
            xmin = int(left * initial_w)
            ymin = int(bottom * initial_h)
            xmax = int(right * initial_w)
            ymax = int(top * initial_h)
 
            box = [xmin, ymin, xmax, ymax]
            cv2.rectangle(picture, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)
            if labels:
                cv2.putText(picture, "%s:%.2f" % (labels[int(detected_classes[0][i]) + 1], score), (box[0], box[1]),
                            font, 0.5, (255, 255, 255), 1)
 
    cv2.imshow("test", picture)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

Logo

更多推荐