视频输入上的 TFLite 推理

2023-12-28

我有一个 SSD tflite 检测模型,正在台式计算机上使用 Python 运行。就目前而言,我的下面的脚本将单个图像作为推理的输入,并且运行良好:

    # Load TFLite model and allocate tensors.
    interpreter = tf.lite.Interpreter(model_path="model.tflite")
    interpreter.allocate_tensors()

    img_resized = Image.open(file_name)
    input_data = np.expand_dims(img_resized, axis=0)
    input_data = (np.float32(input_data) - input_mean) / input_std

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

    interpreter.set_tensor(input_details[0]['index'], input_data)
    interpreter.invoke()
    output_data = interpreter.get_tensor(output_details[0]['index'])

如何对 .mp4 视频作为输入进行推理?

是否也可以从该视频上检测到的对象中绘制边界框?


回答您在视频上运行推理的第一个问题。这是您可以使用的代码。我为分类模型的推理编写了这段代码,因此在您的情况下,output_data变量的输出将采用边界框的形式,您必须使用OpenCV将它们映射到框架上,这也回答了您的第二个问题(绘制边界视频中的方框)。

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

def read_tensor_from_readed_frame(frame, input_height=224, input_width=224,
        input_mean=0, input_std=255):
  output_name = "normalized"
  float_caster = tf.cast(frame, tf.float32)
  dims_expander = tf.expand_dims(float_caster, 0);
  resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
  normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
  sess = tf.Session()
  result = sess.run(normalized)
  return result

def load_labels(label_file):
  label = []
  proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()
  for l in proto_as_ascii_lines:
    label.append(l.rstrip())
  return label

def VideoSrcInit(paath):
    cap = cv2.VideoCapture(paath)
    flag, image = cap.read()
    if flag:
        print("Valid Video Path. Lets move to detection!")
    else:
        raise ValueError("Video Initialization Failed. Please make sure video path is valid.")
    return cap

def main():
  Labels_Path = "labels.txt"
  Model_Path = "model.tflite"
  input_path = "video.mp4"

  ##Loading labels
  labels = load_labels(Labels_Path)

  ##Load tflite model and allocate tensors
  interpreter = tf.lite.Interpreter(model_path=Model_Path)
  interpreter.allocate_tensors()
  # Get input and output tensors.
  input_details = interpreter.get_input_details()
  output_details = interpreter.get_output_details()

  input_shape = input_details[0]['shape']

  ##Read video
  cap = VideoSrcInit(input_path)

  while True:
    ok, cv_image = cap.read()
    if not ok:
      break

    ##Converting the readed frame to RGB as opencv reads frame in BGR
    image = Image.fromarray(cv_image).convert('RGB')

    ##Converting image into tensor
    image_tensor = read_tensor_from_readed_frame(image ,224, 224)

    ##Test model
    interpreter.set_tensor(input_details[0]['index'], image_tensor)
    interpreter.invoke()
    output_data = interpreter.get_tensor(output_details[0]['index'])

    ## You need to check the output of the output_data variable and 
    ## map it on the frame in order to draw the bounding boxes.


    cv2.namedWindow("cv_image", cv2.WINDOW_NORMAL)
    cv2.imshow("cv_image",cv_image)

    ##Use p to pause the video and use q to termiate the program
    key = cv2.waitKey(10) & 0xFF
    if key == ord("q"):
      break
    elif key == ord("p"):
      cv2.waitKey(0)
      continue 
  cap.release()

if __name__ == '__main__':
  main()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

视频输入上的 TFLite 推理 的相关文章

  • 打乱列表并返回副本

    我想对数组进行洗牌 但我找到的只是类似的方法random shuffle x from 在 Python 中随机化字符串列表的最佳方法 https stackoverflow com questions 1022141 best way t
  • 执行不区分大小写的“in”检查并检索原始元素的最简单方法?

    假设 a 有一个字符串列表和一个特定字符串 particular string latitude list Id PRICE LATitude longitude 我想要实现的是执行不区分大小写的检查特定字符串是否在列表中 所以现在我可以这
  • 分类报告 - 精度和 F 分数定义不明确

    我从 sklearn metrics 导入了classification report 当我输入我的np arrays作为参数我收到以下错误 usr local lib python3 6 dist packages sklearn met
  • 反转 Python 整数的位

    给定一个十进制整数 例如 65 如何反转 Python 中的底层位 即以下操作 65 01000001 10000010 130 看来这个任务可以分为三步 将十进制整数转换为二进制表示形式 反转位 转换回十进制 第 2 步和第 3 步看起来
  • 对 numpy 数组的每 n 个元素求平均值

    我有一个 numpy 数组 我想创建一个新数组 它是每个连续三元组元素的平均值 因此 新数组的大小将是原始数组的三分之一 举个例子 np array 1 2 3 1 2 3 1 2 3 应该返回数组 np array 2 2 2 谁能建议一
  • 如何将二维数组作为 multiprocessing.Array 传递给 multiprocessing.Pool?

    我的目标是将父数组传递给mp Pool并填充它2s 同时将其分发到不同的进程 这适用于一维数组 import numpy as np import multiprocessing as mp import itertools def wor
  • 字符串中数字的连续相加

    我是一名正在学习 python 的新程序员 并且在如何完成此任务方面遇到了困难 所以本质上我有一个从文件导入的数字字符串需要读取 并且需要将第一个数字的总和添加到第二个数字并将其转换为正确的 ascii 字符 因此 例如 如果我正在读取字符
  • 代码终止后保持 matplotlib / pyplot 窗口打开

    我希望 python 绘制一个图 在不阻塞控制流的情况下显示它 并在代码退出后使图保持打开状态 这可能吗 这个以及相关的主题存在于许多其他线程中 见下文 但我无法让情节保持开放且非阻塞 例如 如果我使用pyplot ion before p
  • 需要Python字长函数示例

    我的家庭作业有点困难 我本来应该编写一个函数 limitWords 将输入限制为 20 个单词 如果输入超过 20 个单词 则将输入截断为仅 20 个单词 我使用 len text split 作为计算单词的方法 因此 20 个或更少的部分
  • 无法启动 Windows 快捷方式

    我正在尝试使用 python 启动 Windows 我已经尝试了 os system subprocess call os startfile 等多种方法 但总是收到错误消息 指出路径不存在 我知道路径是正确的 因为我尝试在 CMD EXE
  • 将 Python 列表(JSON 或其他)插入 MySQL 数据库

    所以我在Python中有一堆数组数据 嗯 相反 我有一个清单 我试图将此数组存储到 MySQL 数据库中的单个单元格中 我尝试使用 JSON 来序列化我的数据 但也许我不明白 JSON 是如何工作的 因此 在连接到我的数据库后 我尝试了上游
  • 获取每行最后 150 行中所有正值的计数 - pandas

    我有以下数据集 其中有列Date and Values对于每一行 它两者都有 ve and ve价值观 我必须计算最后 150 行的所有正值 在每一行 因此前 150 行将具有空值 然后 以下行将具有最后 150 行的计数 ve行 类似地
  • 使用 python3 查找表情符号的宽度

    我尝试使用 python 中的模式打印字母 A def printA length height symbol a for i in range length for i in range height for i in range hei
  • 使用unittest时如何知道每次测试花费的时间?

    Unittest 仅显示运行所有测试所花费的总时间 但不单独显示每个测试所花费的时间 使用unittest时如何添加每个测试的计时 我想 目前不可能 http bugs python org issue4080 http bugs pyth
  • 初始化整数变量以进行比较

    我正在学习麻省理工学院的开放课件课程计算机科学和 Python 编程简介 https ocw mit edu courses electrical engineering and computer science 6 0001 introd
  • Python列表错误还是我错了?

    我构建了一个 3 级嵌套列表 run on Python 3 2 3 32 bit on Win 7 L2 list 0 for i in range 2 L3 list L2 for i in range 3 L4 list L3 for
  • 如何重写一个列表列表,使值的“孤岛”彼此唯一?

    假设我有一个列表列表 或更概念上准确的二维数组 list 1 1 0 0 0 1 1 2 0 0 0 2 2 2 0 0 0 0 2 0 0 0 0 1 0 我想识别具有相同值的不同区域并重写列表 以便每个区域都有唯一的值 如下所示 lis
  • Django 自定义文件存储系统

    我有一个自定义存储 import os from django core files storage import Storage class AlwaysOverwriteFileSystemStorage Storage def get
  • 使用 Pandas 来“applymap”来访问索引/列?

    解决以下 pandas 问题的最有效方法是什么 这是一个简化的示例 其中包含数据框中的一些数据 import pandas as pd import numpy as np df pd DataFrame np random randint
  • pyodbc 无法正确处理 unicode 数据

    我确实使用 pyodbc 成功连接了 MySQL 数据库 并且它可以很好地处理 ascii 编码的数据 但是当我打印使用 unicode utf8 编码的数据时 它引发了错误 UnicodeEncodeError ascii codec c

随机推荐