如何在运行 Tensorflow 推理会话之前批处理多个视频帧

2024-04-21

我做了一个项目,基本上使用谷歌对象检测 API 和张量流。

我所做的就是使用预先训练的模型进行推理:这意味着实时对象检测,其中输入是网络摄像头的视频流或使用 OpenCV 的类似内容。

现在我得到了相当不错的性能结果,但我想进一步提高 FPS。

因为我的经验是,Tensorflow 在推理时使用了我的整个内存,但 GPU 使用率根本没有达到最大值(NVIDIA GTX 1050 笔记本电脑上约为 40%,NVIDIA Jetson Tx2 上约为 6%)。

所以我的想法是通过增加每个会话运行中输入的图像批量大小来增加 GPU 使用率。

所以我的问题是:在将输入视频流的多个帧提供给它们之前,如何将它们一起批处理sess.run()?

看看我的代码object_detetection.py在我的 github 仓库上:(https://github.com/GustavZ/realtime_object_detection https://github.com/GustavZ/realtime_object_detection).

如果您能提出一些提示或代码实现,我将非常感激!

import numpy as np
import os
import six.moves.urllib as urllib
import tarfile
import tensorflow as tf
import cv2


# Protobuf Compilation (once necessary)
os.system('protoc object_detection/protos/*.proto --python_out=.')

from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
from stuff.helper import FPS2, WebcamVideoStream

# INPUT PARAMS
# Must be OpenCV readable
# 0 = Default Camera
video_input = 0
visualize = True
max_frames = 300 #only used if visualize==False
width = 640
height = 480
fps_interval = 3
bbox_thickness = 8

# Model preparation
# What model to download.
MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'
MODEL_FILE = MODEL_NAME + '.tar.gz'
DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'
# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = 'models/' + MODEL_NAME + '/frozen_inference_graph.pb'
# List of the strings that is used to add correct label for each box.
LABEL_MAP = 'mscoco_label_map.pbtxt'
PATH_TO_LABELS = 'object_detection/data/' + LABEL_MAP
NUM_CLASSES = 90

# Download Model    
if not os.path.isfile(PATH_TO_CKPT):
    print('Model not found. Downloading it now.')
    opener = urllib.request.URLopener()
    opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
    tar_file = tarfile.open(MODEL_FILE)
    for file in tar_file.getmembers():
      file_name = os.path.basename(file.name)
      if 'frozen_inference_graph.pb' in file_name:
        tar_file.extract(file, os.getcwd())
    os.remove('../' + MODEL_FILE)
else:
    print('Model found. Proceed.')

# Load a (frozen) Tensorflow model into memory.
detection_graph = tf.Graph()
with detection_graph.as_default():
  od_graph_def = tf.GraphDef()
  with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
    serialized_graph = fid.read()
    od_graph_def.ParseFromString(serialized_graph)
    tf.import_graph_def(od_graph_def, name='')

# Loading label map
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

# Start Video Stream
video_stream = WebcamVideoStream(video_input,width,height).start()
cur_frames = 0
# Detection
with detection_graph.as_default():
  with tf.Session(graph=detection_graph) as sess:
    # Definite input and output Tensors for detection_graph
    image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
    # Each box represents a part of the image where a particular object was detected.
    detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
    # Each score represent how level of confidence for each of the objects.
    # Score is shown on the result image, together with the class label.
    detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
    detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
    num_detections = detection_graph.get_tensor_by_name('num_detections:0')
    # fps calculation
    fps = FPS2(fps_interval).start()
    print ("Press 'q' to Exit")
    while video_stream.isActive():
      image_np = video_stream.read()
      # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
      image_np_expanded = np.expand_dims(image_np, axis=0)
      # Actual detection.
      (boxes, scores, classes, num) = sess.run(
          [detection_boxes, detection_scores, detection_classes, num_detections],
          feed_dict={image_tensor: image_np_expanded})
      # Visualization of the results of a detection.
      vis_util.visualize_boxes_and_labels_on_image_array(
          image_np,
          np.squeeze(boxes),
          np.squeeze(classes).astype(np.int32),
          np.squeeze(scores),
          category_index,
          use_normalized_coordinates=True,
          line_thickness=bbox_thickness)
      if visualize:
          cv2.imshow('object_detection', image_np)
          # Exit Option
          if cv2.waitKey(1) & 0xFF == ord('q'):
              break
      else:
          cur_frames += 1
          if cur_frames >= max_frames:
              break
      # fps calculation
      fps.update()

# End everything
fps.stop()
video_stream.stop()     
cv2.destroyAllWindows()
print('[INFO] elapsed time (total): {:.2f}'.format(fps.elapsed()))
print('[INFO] approx. FPS: {:.2f}'.format(fps.fps()))

嗯,我只是收集batch_size框架并喂养它们:

batch_size = 5
while video_stream.isActive():
  image_np_list = []
  for _ in range(batch_size):
      image_np_list.append(video_stream.read())
      fps.update()
  # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  image_np_expanded = np.asarray(image_np_list)
  # Actual detection.
  (boxes, scores, classes, num) = sess.run(
      [detection_boxes, detection_scores, detection_classes, num_detections],
      feed_dict={image_tensor: image_np_expanded})

  # Visualization of the results of a detection.
  for i in range(batch_size):
      vis_util.visualize_boxes_and_labels_on_image_array(
          image_np_expanded[i],
          boxes[i],
          classes[i].astype(np.int32),
          scores[i],
          category_index,
          use_normalized_coordinates=True,
          line_thickness=bbox_thickness)
          if visualize:
              cv2.imshow('object_detection', image_np_expanded[i])
              # Exit Option
              if cv2.waitKey(1) & 0xFF == ord('q'):
                  break

当然,如果您正在读取检测结果,则必须在此之后进行相关更改,因为它们现在将具有batch_size rows.

但要小心:在tensorflow 1.4之前(我认为),对象检测API仅支持批量大小为 1 https://github.com/tensorflow/models/issues/1816 in image_tensor,所以除非你升级你的张量流,否则这将不起作用。

另请注意,您生成的 FPS 将是平均值,但同一批次中的帧实际上比不同批次之间的时间更接近(因为您仍然需要等待sess.run()完成)。尽管两个连续帧之间的最大时间应该增加,但平均值仍应明显优于当前的 FPS。

如果您希望帧之间的间隔大致相同,我想您将需要更复杂的工具,例如多线程和队列:一个线程将从流中读取图像并将其存储在队列中,另一个线程将需要他们从队列中出来并打电话sess.run()异步处理它们;它还可以告诉第一个线程根据其自身的计算能力加快或减慢速度。这实施起来比较棘手。

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

如何在运行 Tensorflow 推理会话之前批处理多个视频帧 的相关文章

随机推荐

  • Angular js - 幻灯片视图但不是主页 - ng-animate

    我在用着ng动画滑动应用程序视图 因此每个路线都会滑动自己的视图 这是我的简单代码 html div class slide div css Animations slide left 0 slide ng enter transition
  • 在 JavaScript 中从 Base64 字符串创建 BLOB

    我在字符串中有 Base64 编码的二进制数据 const contentType image png const b64Data iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQV
  • 从 webview 获取用户触摸的元素

    大家好 我正在尝试获取用户在 web 视图中触摸的 html 元素 例如 该场景是用户触摸 Web 视图中的某种按钮 应用程序显示该按钮的 html 代码 如下所示 a href index html a 我已经能够获取用户正在浏览的 ht
  • 为什么我在显式调用构造函数时无法引用实例方法?

    有谁知道为什么你可以参考static构造函数第一行中的方法使用this or super 但不是非静态方法 考虑以下工作 public class TestWorking private A a null public TestWorkin
  • 将 UTF-8 编码的转储加载到 MySQL 中

    昨天我为这个问题苦苦思索了几个小时 我在 MySQL 4 1 22 服务器上有一个数据库 编码设置为 UTF 8 Unicode utf8 如 phpMyAdmin 报告 该数据库中的表的默认字符集设置为latin2 但是 使用它的 Web
  • 如何调整 NLTK 句子标记器

    我正在使用 NLTK 来分析一些经典文本 但我在按句子标记文本时遇到了麻烦 例如 这是我从以下内容中得到的片段莫比迪克 http www gutenberg org cache epub 2701 pg2701 txt import nlt
  • 如何对计算值进行排序?

    我目前正在建立一个 NFL 选秀联盟网站 我有一个用户模型 一个游戏模型和一个连接表 用于捕获每个用户的个人选择 游戏模型具有 结果 属性 其中 W 表示获胜 L 表示失败 P 表示推动 平局 我在构建排名页面时遇到问题 目前我的用户模型中
  • 将 cURL json 数组响应转换为关联数组

    我有一个像这样的 cURL 请求 ch curl init data filter year StartTime urlencode eq 2013 and month StartTime urlencode eq 06 curl seto
  • Jenkins Slack 集成

    我想使用 Jenkins 中的 Slack 插件将通知发送到 Slack 通道 当我测试连接时 Jenkins 表示成功 但我在 Slack 频道中没有收到任何通知 是否存在任何已知问题 如何让 Jenkins 向 Slack 发送通知 我
  • 操作栏图标大小

    根据操作栏图标 https developer android com guide practices ui guidelines icon design action bar html size11mdpi 屏幕的操作栏图标应为 24 x
  • 如何使用 Slick 3.0 编写可读的嵌套连接查询

    此代码创建一个查询 用于在 Web 后端检索用户的个人资料 它创建一个查询 将必要的信息组装到 DTO 这只是一个案例类 中 随后以 JSON 形式发回 def getProfile userId Long val q for u p a
  • 从 powershell 脚本调用可执行文件(带参数)

    我正在从 powershell 调用 zip 实用程序 但很难直接获取其参数 这是代码 if not test path C Program Files x86 7 Zip 7z exe throw C Program Files x86
  • 创建嵌套 ul li 的 PHP 函数?

    我正在尝试将一个小型 CMS 附加到我正在创建的网站 不过我遇到了一个小问题 CMS 使用 PHP 函数插入菜单 这些 PHP 函数创建 HTML 我希望使用的特定函数 treemenu 创建一个嵌套的 ul li 然后可将其用于下拉菜单
  • 如何更改此 html 用户表单上的日期格式

    我有将数据输入 mysql DB 的 html 表单 但在日期的输入字段中它具有以下格式 mm dd yyyy 但我更喜欢在输入日期时使用这种格式 dd mm yyyy 任何机构都可以帮助更改格式吗 这里是 HTML 表单 p Admiti
  • IDispatchEx 存在于哪里?

    找不到包含 IDispatchEx 接口的库 我想实现这个接口 但是找不到 有谁知道它在哪里吗 谢谢 保罗 如果您想编写一个实现的托管类IDispatchEx http msdn microsoft com en us library sk
  • 带有 Kafka 消费者的 Spring Boot 作业调度程序

    我正在开发一个 POC 我想使用来自 Kafka 主题 用户 的消息 尝试实现消费者应该从 Kafka 主题读取消息 一旦 spring boot 调度程序在预定时间或 cron 时间触发 那么我们应该开始从 kafka 主题中一一消费现有
  • 如何更改 richfaces 组合框提出的建议?

    我目前正在玩 richfaces 组合框 你可以检查是 我想知道是否有办法改变在组合框中提出建议的方式 而不是仅建议以同一字母开头的单词 而是建议具有以该字母或字母组合开头的其他单词的单词 这是演示中的示例 从当前的组合框中 如果我输入 M
  • WKWebView 评估 Javascript 而不重新加载页面

    目前我只能通过将 javascript 添加到 webview 的配置的 userContentController 并重新加载页面来弄清楚如何评估 javascript 如下所示 WKUserScript script WKUserScr
  • 如果
    中的操作字段有参数会发生什么?

    如果我在 HTML 中执行以下操作 是否会出现一个得到良好支持的常见行为
  • 如何在运行 Tensorflow 推理会话之前批处理多个视频帧

    我做了一个项目 基本上使用谷歌对象检测 API 和张量流 我所做的就是使用预先训练的模型进行推理 这意味着实时对象检测 其中输入是网络摄像头的视频流或使用 OpenCV 的类似内容 现在我得到了相当不错的性能结果 但我想进一步提高 FPS