【问题标题】:How to use yolov5 tflite export with OpenCV如何在 OpenCV 中使用 yolov5 tflite 导出
【发布时间】:2022-07-19 16:20:48
【问题描述】:

我从 Yolov5 导出了一个 tflite 文件,并使用以下代码获得了输出数据:

import numpy as np
import tensorflow as tf
from PIL import Image
import os

img = Image.open(os.path.join('dataset', 'images','val','IMG_6099.JPG'))
img = img.resize((256,256),Image.ANTIALIAS)
numpydata = np.asarray(img)
interpreter = tf.lite.Interpreter(model_path="yolov5s-fp16.tflite")
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

input_shape = input_details[0]['shape']
input_data = np.array(img,dtype=np.float32)
input_data = tf.expand_dims(input_data, 0)
interpreter.set_tensor(input_details[0]['index'], input_data)

interpreter.invoke()

output_data = interpreter.get_tensor(output_details[0]['index'])

打印出output_data:

[[[1.6754180e-02 3.2771632e-02 8.4546164e-02 ... 2.2025524e-05
   3.0189141e-05 6.1972853e-05]
  [1.5505254e-02 3.5847023e-02 9.6953809e-02 ... 1.9333076e-05
   1.5587271e-05 3.6931968e-05]
  [1.6107641e-02 3.6390714e-02 8.2990780e-02 ... 1.6197217e-05
   1.4623029e-05 3.6216315e-05]
  ...
  [8.6931992e-01 8.8494051e-01 2.4040593e-01 ... 3.1457843e-05
   2.4052188e-05 2.2471884e-05]
  [8.6244017e-01 9.0521729e-01 4.4481179e-01 ... 5.1936011e-05
   3.9207229e-05 3.5609013e-05]
  [8.6841702e-01 9.0255147e-01 7.0057535e-01 ... 1.0812500e-04
   1.0073676e-04 7.7818921e-05]]]

这些数字是多少?更重要的是如何在图像上显示结果? 我也看到了这个post

这是我尝试实时捕获对象的代码:

cap = cv2.VideoCapture(0)
ret, frame = cap.read()
print(ret)
frame = cv2.resize(frame, (256 , 256))
    

for i in range(len(scores)):
    if ((scores[i] > 0.1) and (scores[i] <= 1.0)):
        H = frame.shape[0]
        W = frame.shape[1]
        xmin = int(max(1,(xyxy[0][i] * W)))
        ymin = int(max(1,(xyxy[1][i] * H)))
        xmax = int(min(H,(xyxy[2][i] * W)))
        ymax = int(min(W,(xyxy[3][i] * H)))

        # cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)
plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))

【问题讨论】:

  • 附件中的解释很清楚。输出包含边界框、类标签和置信度分数。
  • 是的,但我真的很困惑如何实时使用它,我用我迄今为止所做的编辑了这篇文章。内核将在进程中间停止。@JeruLuke

标签: tensorflow opencv pytorch object-detection yolov5


【解决方案1】:

你附上的帖子很清楚地说: [x ,y ,w ,h , conf, class0, class1, ...] 总共 85 列和许多对象(行)检测到。 col 0-3是boxes,col 4是conf,另外80是class

您需要使用 conf 过滤行。否则你会得到很多错误的检测对象。

另外 [x ,y ,w ,h] 不是您输入图像的真实比例。

要获得真实的盒子,您可能需要进行一些处理,例如重新缩放、xywh 到 xyxy、NMS(非最大抑制)等。

您可以查看 Yolov5 源代码中的 detect.py 和 utils/general.py。

得到真正的盒子后,在图像上绘制盒子。

下面的文档向您展示如何使用 open cv 在图像上绘制框 https://docs.opencv.org/4.x/dc/da5/tutorial_py_drawing_functions.html

如果你google,有很多例子教你如何使用open cv绘图

【讨论】:

    猜你喜欢
    • 2022-11-10
    • 2022-07-09
    • 2023-01-17
    • 2021-04-25
    • 2022-07-26
    • 2021-08-11
    • 2022-01-10
    • 2022-12-25
    • 2021-06-16
    相关资源
    最近更新 更多