TensorFlow:将自己训练好的模型迁移到电脑摄像头和外置海康摄像头上,并在视频中实时检测

本文主要是介绍TensorFlow:将自己训练好的模型迁移到电脑摄像头和外置海康摄像头上,并在视频中实时检测,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

有了训练好的模型之后,可以将模型迁移到电脑或者手机上

电脑:

# -*- coding: utf-8 -*-
"""@author: Terry n
"""
# Imports
import numpy as np
import os
import sys
import tensorflow as tf
import cv2# if tf.__version__ < '1.4.0':
#     raise ImportError('Please upgrade your tensorflow installation to v1.4.* or later!')os.chdir('D:\\object_detection_api\\models-master\\research\\object_detection')# Env setup
# This is needed to display the images.
# %matplotlib inline# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")# Object detection imports
from utils import label_map_utilfrom utils import visualization_utils as vis_util# Model preparation
# What model to download.
#MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'  # [30,21]  best
# MODEL_NAME = 'ssd_inception_v2_coco_2017_11_17'            #[42,24]
# MODEL_NAME = 'faster_rcnn_inception_v2_coco_2017_11_08'         #[58,28]
# MODEL_NAME = 'faster_rcnn_resnet50_coco_2017_11_08'     #[89,30]
# MODEL_NAME = 'faster_rcnn_resnet50_lowproposals_coco_2017_11_08'   #[64, ]
# MODEL_NAME = 'rfcn_resnet101_coco_2017_11_08'    #[106,32]
# MODEL_NAME = 'faster_rcnn_inception_resnet_v2_atrous_coco_2018_01_28'
# MODEL_NAME = 'ssdlite_mobilenet_v2_coco_2018_05_09'
MODEL_NAME = 'fod_detection'# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'# List of the strings that is used to add correct label for each box.
#PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')
PATH_TO_LABELS = os.path.join('data', 'fod.pbtxt')#NUM_CLASSES = 90
NUM_CLASSES = 1
# 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)# Helper code
def load_image_into_numpy_array(image):(im_width, im_height) = image.sizereturn np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)# Size, in inches, of the output images.
# IMAGE_SIZE = (12, 8)with detection_graph.as_default():with tf.Session(graph=detection_graph) as sess:# Definite input and output Tensors for detection_graphimage_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')# the video to be detected, eg, "test.mp4" herevidcap = cv2.VideoCapture(0)# Default resolutions of the frame are obtained.The default resolutions are system dependent.# We convert the resolutions from float to integer.frame_width = int(vidcap.get(3))frame_height = int(vidcap.get(4))while (True):ret, image = vidcap.read()if ret == True:# image_np = load_image_into_numpy_array(image)image_np = image# 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=8)print(scores)cv2.imshow("capture",image_np)if cv2.waitKey(1) & 0xFF == ord('q'):ret = False# Break the loopelse:break
vidcap.release()
cv2.destroyAllWindows()

注意:1,第十八行定位到你的object_detection文件夹下。

2,43行,47行定位到模型位置。50,51行相继修改。54行num_classes为1

3,注意,将此model_video的python文件定位到object_detection下,再在anaconda下运行。

海康摄像头:

model_video.py

# -*- coding: utf-8 -*-
"""@author: Terry n
"""
# Imports
import numpy as np
import os
import sys
import tensorflow as tf
import cv2# if tf.__version__ < '1.4.0':
#     raise ImportError('Please upgrade your tensorflow installation to v1.4.* or later!')os.chdir('D:\\object_detection_api\\models-master\\research\\object_detection')# Env setup
# This is needed to display the images.
# %matplotlib inline# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")# Object detection imports
from utils import label_map_utilfrom utils import visualization_utils as vis_util# Model preparation
# What model to download.
#MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'  # [30,21]  best
# MODEL_NAME = 'ssd_inception_v2_coco_2017_11_17'            #[42,24]
# MODEL_NAME = 'faster_rcnn_inception_v2_coco_2017_11_08'         #[58,28]
# MODEL_NAME = 'faster_rcnn_resnet50_coco_2017_11_08'     #[89,30]
# MODEL_NAME = 'faster_rcnn_resnet50_lowproposals_coco_2017_11_08'   #[64, ]
# MODEL_NAME = 'rfcn_resnet101_coco_2017_11_08'    #[106,32]
# MODEL_NAME = 'faster_rcnn_inception_resnet_v2_atrous_coco_2018_01_28'
# MODEL_NAME = 'ssdlite_mobilenet_v2_coco_2018_05_09'
# MODEL_NAME = 'fod_detection'
MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'# List of the strings that is used to add correct label for each box.
# PATH_TO_LABELS = os.path.join('data', 'fod.pbtxt')
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')NUM_CLASSES = 90
# NUM_CLASSES = 1
# 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)# Helper code
def load_image_into_numpy_array(image):(im_width, im_height) = image.sizereturn np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)# Size, in inches, of the output images.
# IMAGE_SIZE = (12, 8)with detection_graph.as_default():with tf.Session(graph=detection_graph) as sess:# Definite input and output Tensors for detection_graphimage_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')# the video to be detected, eg, "test.mp4" hereurl = 'rtsp://admin:ha515515@192.168.1.64:554/11'# vidcap = cv2.VideoCapture(0)# Default resolutions of the frame are obtained.The default resolutions are system dependent.# We convert the resolutions from float to integer.while (True):vidcap = cv2.VideoCapture(url)ret, image = vidcap.read()frame_width = int(vidcap.get(3))frame_height = int(vidcap.get(4))if ret == True:# image_np = load_image_into_numpy_array(image)image_np = image# 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=8)print(scores)cv2.imshow("capture",image_np)if cv2.waitKey(20) & 0xFF == ord('q'):ret = False# Break the loopelse:break
vidcap.release()
cv2.destroyAllWindows()

3,在视频中实时检测

video_detection.py

# By Terry_n
# https://space.bilibili.com/275177832
# 可以放在任何文件夹下运行(前提正确配置API[环境变量])
# 输出视频没有声音,pr可解决一切import numpy as np
import os
import sys
import tensorflow as tf
import cv2
import timefrom object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_utilstart = time.time()
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
cv2.setUseOptimized(True)  # 加速cv# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")# 可能要改的内容
######################################################
PATH_TO_CKPT = 'D:\\object_detection_api\\models-master\\research\\object_detection\\fod_detection\\fod_frozen_inference_graph.pb'  # 模型及标签地址PATH_TO_LABELS = 'D:\\object_detection_api\\models-master\\research\\object_detection\\data\\fod.pbtxt'video_PATH = "D:\\object_detection_api\\models-master\\research\\object_detection\\test_video\\cycling.mp4"  # 要检测的视频
out_PATH = "D:\\object_detection_api\\models-master\\research\\object_detection\\output_video\\out_cycling1.mp4"  # 输出地址NUM_CLASSES = 1  # 检测对象个数fourcc = cv2.VideoWriter_fourcc(*'DIVX')  # 编码器类型(可选)
# 编码器: DIVX , XVID , MJPG , X264 , WMV1 , WMV2####################################################### 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)# 读取视频
video_cap = cv2.VideoCapture(video_PATH)
fps = int(video_cap.get(cv2.CAP_PROP_FPS))  # 帧率width = int(video_cap.get(3))  # 视频长,宽
hight = int(video_cap.get(4))videoWriter = cv2.VideoWriter(out_PATH, fourcc, fps, (width, hight))config = tf.ConfigProto()
config.gpu_options.allow_growth = True  # 减小显存占用
with detection_graph.as_default():with tf.Session(graph=detection_graph, config=config) as sess:# Definite input and output Tensors for detection_graphimage_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')num = 0while True:ret, frame = video_cap.read()if ret == False:  # 没检测到就跳出breaknum += 1print(num)  # 输出检测到第几帧了# print(num/fps) # 检测到第几秒了image_np = frameimage_np_expanded = np.expand_dims(image_np, axis=0)image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')boxes = detection_graph.get_tensor_by_name('detection_boxes:0')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=4)# 写视频videoWriter.write(image_np)videoWriter.release()
end = time.time()
print("Execution Time: ", end - start)

 

这篇关于TensorFlow:将自己训练好的模型迁移到电脑摄像头和外置海康摄像头上,并在视频中实时检测的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/844817

相关文章

不删数据还能合并磁盘? 让电脑C盘D盘合并并保留数据的技巧

《不删数据还能合并磁盘?让电脑C盘D盘合并并保留数据的技巧》在Windows操作系统中,合并C盘和D盘是一个相对复杂的任务,尤其是当你不希望删除其中的数据时,幸运的是,有几种方法可以实现这一目标且在... 在电脑生产时,制造商常为C盘分配较小的磁盘空间,以确保软件在运行过程中不会出现磁盘空间不足的问题。但在

电脑显示hdmi无信号怎么办? 电脑显示器无信号的终极解决指南

《电脑显示hdmi无信号怎么办?电脑显示器无信号的终极解决指南》HDMI无信号的问题却让人头疼不已,遇到这种情况该怎么办?针对这种情况,我们可以采取一系列步骤来逐一排查并解决问题,以下是详细的方法... 无论你是试图为笔记本电脑设置多个显示器还是使用外部显示器,都可能会弹出“无HDMI信号”错误。此消息可能

电脑多久清理一次灰尘合? 合理清理电脑上灰尘的科普文

《电脑多久清理一次灰尘合?合理清理电脑上灰尘的科普文》聊起电脑清理灰尘这个话题,我可有不少话要说,你知道吗,电脑就像个勤劳的工人,每天不停地为我们服务,但时间一长,它也会“出汗”——也就是积累灰尘,... 灰尘的堆积几乎是所有电脑用户面临的问题。无论你的房间有多干净,或者你的电脑是否安装了灰尘过滤器,灰尘都

Python基于火山引擎豆包大模型搭建QQ机器人详细教程(2024年最新)

《Python基于火山引擎豆包大模型搭建QQ机器人详细教程(2024年最新)》:本文主要介绍Python基于火山引擎豆包大模型搭建QQ机器人详细的相关资料,包括开通模型、配置APIKEY鉴权和SD... 目录豆包大模型概述开通模型付费安装 SDK 环境配置 API KEY 鉴权Ark 模型接口Prompt

Python实现局域网远程控制电脑

《Python实现局域网远程控制电脑》这篇文章主要为大家详细介绍了如何利用Python编写一个工具,可以实现远程控制局域网电脑关机,重启,注销等功能,感兴趣的小伙伴可以参考一下... 目录1.简介2. 运行效果3. 1.0版本相关源码服务端server.py客户端client.py4. 2.0版本相关源码1

闲置电脑也能活出第二春?鲁大师AiNAS让你动动手指就能轻松部署

对于大多数人而言,在这个“数据爆炸”的时代或多或少都遇到过存储告急的情况,这使得“存储焦虑”不再是个别现象,而将会是随着软件的不断臃肿而越来越普遍的情况。从不少手机厂商都开始将存储上限提升至1TB可以见得,我们似乎正处在互联网信息飞速增长的阶段,对于存储的需求也将会不断扩大。对于苹果用户而言,这一问题愈发严峻,毕竟512GB和1TB版本的iPhone可不是人人都消费得起的,因此成熟的外置存储方案开

流媒体平台/视频监控/安防视频汇聚EasyCVR播放暂停后视频画面黑屏是什么原因?

视频智能分析/视频监控/安防监控综合管理系统EasyCVR视频汇聚融合平台,是TSINGSEE青犀视频垂直深耕音视频流媒体技术、AI智能技术领域的杰出成果。该平台以其强大的视频处理、汇聚与融合能力,在构建全栈视频监控系统中展现出了独特的优势。视频监控管理系统EasyCVR平台内置了强大的视频解码、转码、压缩等技术,能够处理多种视频流格式,并以多种格式(RTMP、RTSP、HTTP-FLV、WebS

大模型研发全揭秘:客服工单数据标注的完整攻略

在人工智能(AI)领域,数据标注是模型训练过程中至关重要的一步。无论你是新手还是有经验的从业者,掌握数据标注的技术细节和常见问题的解决方案都能为你的AI项目增添不少价值。在电信运营商的客服系统中,工单数据是客户问题和解决方案的重要记录。通过对这些工单数据进行有效标注,不仅能够帮助提升客服自动化系统的智能化水平,还能优化客户服务流程,提高客户满意度。本文将详细介绍如何在电信运营商客服工单的背景下进行

Andrej Karpathy最新采访:认知核心模型10亿参数就够了,AI会打破教育不公的僵局

夕小瑶科技说 原创  作者 | 海野 AI圈子的红人,AI大神Andrej Karpathy,曾是OpenAI联合创始人之一,特斯拉AI总监。上一次的动态是官宣创办一家名为 Eureka Labs 的人工智能+教育公司 ,宣布将长期致力于AI原生教育。 近日,Andrej Karpathy接受了No Priors(投资博客)的采访,与硅谷知名投资人 Sara Guo 和 Elad G

综合安防管理平台LntonAIServer视频监控汇聚抖动检测算法优势

LntonAIServer视频质量诊断功能中的抖动检测是一个专门针对视频稳定性进行分析的功能。抖动通常是指视频帧之间的不必要运动,这种运动可能是由于摄像机的移动、传输中的错误或编解码问题导致的。抖动检测对于确保视频内容的平滑性和观看体验至关重要。 优势 1. 提高图像质量 - 清晰度提升:减少抖动,提高图像的清晰度和细节表现力,使得监控画面更加真实可信。 - 细节增强:在低光条件下,抖