第三章 利用TensorFlow Object Detection API实现摄像头实时物体检测

2023-11-05

通过第二章节,已经在Ubuntu16.04上实现了利用Google的TensorFlow Object Detection API对图片上物体的检测。这一部分在此基础上修改代码实现捕捉摄像头视频流,并对视频流实时物体检测。

1、安装opencv-python

安装opencv直接在终端执行:

sudo pip install opencv-python

查看opencv版本,执行:

pkg-config --modversion opencv

下图表安装成功 ,我的是3.3.1

下面写一个测试代码实现摄像头实时捕捉: 

import cv2
import numpy as np

cap = cv2.VideoCapture(0)
while(1):
    # get a frame
    ret, frame = cap.read()
    # show a frame
    cv2.imshow("capture", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows() 

 同样在jupyter上点击run all,或者按Shift+Eenter,就会显示出视频流

2、修改代码实现实时物体检测 

代码根据research/object_detection路径的object_detection_tutorial.ipynb修改而来,其中红色字体的步骤的代码需要修改。

(1)导入各种包,代码不变

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

from distutils.version import StrictVersion
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image

# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")
from object_detection.utils import ops as utils_ops

if StrictVersion(tf.__version__) < StrictVersion('1.9.0'):
    raise ImportError('Please upgrade your TensorFlow installation to v1.9.* or later!')

(2)增加导入cv包,以及获取摄像头设备号

import cv2
cap = cv2.VideoCapture(0)

 (3)从utils模块引入label_map_util和visualization_utils

这两个包很关键,label_map_util用于后面获取图像标签和类别,visualization_utils用于可视化。代码不变

from utils import label_map_util
from utils import visualization_utils as vis_util

(4)获取预训练模型

模型下载地址:https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md

里面包含很多预训练好的模型,各个模型的speed、mAP都给了参考,其中数据集为COCO(90个类别)

我选择了速度较快的ssd_mobilenet_v1_coco ,下载后解压到research/object_detection路径。

然后添加模型路径:

CWD_PATH = os.getcwd()
PATH_TO_CKPT = os.path.join(CWD_PATH,'ssd_mobilenet_v1_coco_2017_11_17','frozen_inference_graph.pb')

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join(CWD_PATH,'data', 'mscoco_label_map.pbtxt')

NUM_CLASSES = 90

(5)加载模型,代码不变

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='')

(6)加载lable 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)

 (7)最后核心代码

with detection_graph.as_default():
    with tf.Session(graph=detection_graph) as sess:
        while True:
            ret, image_np = cap.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)
            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.
            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.
            scores = detection_graph.get_tensor_by_name('detection_scores:0')
            classes = detection_graph.get_tensor_by_name('detection_classes:0')
            num_detections = detection_graph.get_tensor_by_name('num_detections:0')
            # Actual detection.
            (boxes, scores, classes, num_detections) = sess.run(
                [boxes, scores, 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=8)

            cv2.imshow('object detection', cv2.resize(image_np, (800,600)))
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break
cap.release()
cv2.destroyAllWindows()

3、测试

附完整代码:

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

from distutils.version import StrictVersion
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image

# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")
from object_detection.utils import ops as utils_ops

if StrictVersion(tf.__version__) < StrictVersion('1.9.0'):
    raise ImportError('Please upgrade your TensorFlow installation to v1.9.* or later!')
import cv2
cap = cv2.VideoCapture(0)
from utils import label_map_util
from utils import visualization_utils as vis_util
CWD_PATH = os.getcwd()
PATH_TO_CKPT = os.path.join(CWD_PATH,'ssd_mobilenet_v1_coco_2017_11_17','frozen_inference_graph.pb')

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join(CWD_PATH,'data', 'mscoco_label_map.pbtxt')

NUM_CLASSES = 90
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='')
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)
with detection_graph.as_default():
    with tf.Session(graph=detection_graph) as sess:
        while True:
            ret, image_np = cap.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)
            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.
            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.
            scores = detection_graph.get_tensor_by_name('detection_scores:0')
            classes = detection_graph.get_tensor_by_name('detection_classes:0')
            num_detections = detection_graph.get_tensor_by_name('num_detections:0')
            # Actual detection.
            (boxes, scores, classes, num_detections) = sess.run(
                [boxes, scores, 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=8)

            cv2.imshow('object detection', cv2.resize(image_np, (800,600)))
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break
cap.release()
cv2.destroyAllWindows()

 结果图:

 

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

第三章 利用TensorFlow Object Detection API实现摄像头实时物体检测 的相关文章

随机推荐

  • sklearn中的fit_transform和transform以及什么时候使用

    在使用sklearn对数据进行预处理的时候很有可能会遇到fit transform和transform 网上不少资料写的模棱两可 在这里我回答几个核心问题 也许看完我写的这篇文章 一些疑惑就会豁然开朗 为什么在训练集进行fit而不在测试集f
  • c++的并归排序怎么写

    答 C 的并归排序的写法如下 1 如果数组只有一个元素 则返回该元素 2 否则 将数组分成两半 3 使用递归 对每一半进行并归排序 4 将排序后的两个子数组合并 5 返回排序后的结果
  • C语言回调函数一个简单的例子

    回调函数通俗的解释 普通函数 你所写的函数调用系统函数 你只管调用 不管实现 回调函数 系统调用你所写的函数 你只管实现 不管调用 以下是使用 语言实现回调函数的一个例子 代码 include
  • Microsoft Excel 无法插入新的单元格,因为这会将非空单元格推送到工作表的末尾...的问题解决

    这个问题的出现应该是最后一行或一列有数据 按以下步骤操作 1 选中文字表格最后一列空白列 随后按ctrl shift 向右 选中整列 点击右键删除 2 选中文字表格最后一行空白列 随后按ctrl shift 向右 选中整行 点击右键删除
  • Springboot 集成 Groovy Script 完整示例

    Springboot 集成 Groovy Script 完整示例 使用Spring Boot集成Groovy Script来实现动态规则解析和执行的Demo 以下是实现步骤 1 创建Spring Boot项目 首先 创建一个Spring B
  • 测试代码(测试函数、测试类)

    测试函数 def get name first last full name first last return full name title from name import get name print Enter q at any
  • Using a Single Business Pattern with the RUP -part3

    Using IBM Patterns for e business during inceptionKey goals of the RUP inception phase are A vision that establishes the
  • 逆向工程Python爬虫——国税局发票查验平台

    前言 这是一篇含金量很高的干货文章 笔者将手把手带领各位一步一步地实现爬取国家税务总局全国增值税发票查验平台 以下简称 查验平台 这个想法诞生在19年初 当时在做一款通过扫描二维码就可以查验发票的小程序 当时由于笔者学艺尚浅 没办法模拟请求
  • 浏览器localStorage

    Window localStorage 属性 JavaScript 存储对象 JavaScript 存储对象 实例 使用 localStorage 创建一个本地存储的 name value 对 name lastname value Smi
  • 解决jupyter notebook打开时找不到想要的文件

    原因 打开notebook默认显示的是当前目录下的文件 标题 解决办法 打开cmd用dos命令将当前目录切换到想用notebook打开的文件所在的文件夹 已经切换到了文件所在的目录 所以用命令jupyter notebook打开notebo
  • 重装pytorch历程-问题-解决

    用conda install时报错 An HTTP error occurred when trying to retrieve this URL HTTP errors are often intermittent 我要做的事 想使用to
  • 微软D365 入门文章汇总以及各项认证介绍(持续跟新.....)

    介绍 希望入门D365的同学们 需要具备的知识点 涉及C WebApi 前端知识 Power Platform等知识 以及Azure的知识点等 需要有了解 实施Microsoft Dynamics 365 CE 12章 实施Microsof
  • 多线程异常 和 事务(一)

    1 首先提出几个问题 1 1 子线程中的异常在主线程中是否可以catch 1 2 在spring中主线程有事务 那么子线程中有事务码 2 先看第一个问题 2 1 我们在main方法里面测试 代码如下 package com pingan t
  • 理解 glibc malloc:malloc() 与 free() 原理图解

    本文分为三个等级自顶向下地分析了glibc中内存分配与回收的过程 本文不过度关注细节 因此只是分别从arena层次 bin层次 chunk层次进行图解 而不涉及有关指针的具体操作 前言 Arena级分析 main arena中的内存申请 t
  • QuickLook搭配Everthing提高工作效率

    因为我的Everthing已经默认以管理员启动了 所以QuickLook也要以管理员权限启动才能查看Everthing中的文件 而QuickLook本身不能以管理员权限启动 所以需要在任务计划程序中设置 步骤 Ctrl R打开CMD 输入t
  • C++模板与泛型编程

    前言 泛型是独立于任何特定类型的编码 在C 中 我们经常使用的容器vector 该容器可以定义不同种类的vector 如vector list vector list或自定义类型等 函数模板 如果要编写一个函数来比较两个数的大小 返回其中最
  • sklearn逻辑回归参数设置_【机器学习笔记】:逻辑回归实战练习(二)

    作者 xiaoyu 微信公众号 Python数据科学 知乎 python数据分析师 前言 前几篇介绍了逻辑回归在机器学习中的重要性 5个原因告诉你 为什么在成为数据科学家之前 逻辑回归 是第一个需要学习的 以及逻辑回归的理论和公式推导 路远
  • Python报错ModuleNotFoundError: No module named ‘tensorflow.contrib‘ 的解决

    在GitHub上下载的image captioning的代码 运行时发现报错为ModuleNotFoundError No module named tensorflow contrib 在CSDN和GitHub上查询后发现是TensorF
  • VS Code插件推荐(一)

    1 Power Mode 炫酷的输入特效 2 Rainbow Theme 炫酷的字体颜色 让枯燥的代码多了一丝生机 3 koroFileHeader 趣味头文件注释 4 Chinese 汉化插件 5 Bracket Pair Coloriz
  • 第三章 利用TensorFlow Object Detection API实现摄像头实时物体检测

    通过第二章节 已经在Ubuntu16 04上实现了利用Google的TensorFlow Object Detection API对图片上物体的检测 这一部分在此基础上修改代码实现捕捉摄像头视频流 并对视频流实时物体检测 1 安装openc