中培伟业IT资讯频道
您现在的位置:首页 > IT资讯 > 软件研发 > Python实时对象检测入门指南

Python实时对象检测入门指南

2020-08-05 18:12:35 | 来源:中培企业IT培训网

  称为计算机视觉或CV的特定领域具有广泛的现代应用程序。从被自动驾驶汽车用作道路目标检测到复杂的面部和肢体语言识别(可以识别可能的犯罪或犯罪活动),CV在当今世界中有很多用途。不可否认,对象检测还是Computer Vision最酷的应用之一。当今的CV工具可以轻松地在图像甚至是实时流视频上实现对象检测。在此处,我们将看一下使用TensorFlow进行实时对象检测的简单演示。

  设置简单的对象检测器

  先决条件:

  Tensorflow> = 1.15.0

  通过执行pip install tensorflow安装最新版本

  营造环境

  步骤1.下载或克隆TensorFlow对象检测代码到本地计算机中

  在终端中执行以下命令:git clone如果您的计算机上未安装git,则可以选择从此处下载zip文件。

  步骤2.安装依赖项

  下一步是确保我们拥有在计算机上运行对象检测器所需的所有库和模块。

  (是情况下,大多数依赖项都随随Tensorflow一起提供)

  ·赛顿

  ·contextlib2

  ·枕头

  ·xml文件

  ·matplotlib

  如果您发现任何任何模块,只需在您的环境中执行pip install即可安装。

步骤3.安装Protobuf编译器

  Protobuf或Protocol示例是Google的语言无关,平台无关的可扩展机制,用于序列化结构化数据。它可以帮助我们定义我们希望数据的结构方式,一旦结构化,就可以轻松地使用各种语言在各种数据流之间读写结构化数据。

  这也是该项目的依赖项。您可以在此处了解有关Protobufs的更多信息。现在,选择适合您的操作系统的版本,然后复制下载链接。

  :终端或命令向导,将目录更改为克隆的存储库,然后在终端中执行以下命令。

  cd模型/研究

  wget -O protobuf.zip 

  解压缩protobuf.zip

  注意:请确保在模型/研究目录中解压缩protobuf.zip文件

  步骤4.编译Protobuf编译器

  从研究/目录执行以下命令以编译协议捆绑。

  在Python中实现对象检测

  现在,我们已经安装了所有依赖项,让我们使用Python来实现对象检测。

  在此目录中,您将找到一个名为object_detection_tutorial.ipynb的ipython笔记本。该文件是用于对象检测的演示,执行时将使用指定的“ ssd_mobilenet_v1_coco_2017_11_17模型对存储库中提供的两个测试图像进行分类。

  以下是测试输出之一:

  在相同的文件夹中制作一个新的Jupyter笔记本,并遵循以下代码。

  在[1]中:

  import numpy as npimport osimport six.moves.urllib as urllibimport sysimport tarimport import tensorflow as tfimport zipfile from distutils.version import strictVersionfrom collections import defaultdictfrom io import matplotlib import pyplot as plt from PIL import Image#这是必需的,因为笔记本存储在object_中。

  utils中的sys.path.append(“ ..”)作为utils_opsif StrictVersion(tf .__ version__)<StrictVersion('1.12.0'):

  提高ImportError('请将您的TensorFlow安装升级到v1.12。*。')

  在[2]中:

  #这是显示图像所必需的。

  get_ipython()。run_line_magic('matplotlib','inline')

  在[3]中:

  #对象检测导入#这是来自对象检测模块的导入。from utils import label_map_utilfrom utils import visualization_utils as vis_util

  在[4]中:

  #模型准备#使用`export_inference_graph.py`工具导出的任何模型都可以通过更改`PATH_TO_FROZEN_GRAPH`指向新的.pb文件来加载。#默认情况下,我们在此处使用“带有Mobilenet的SSD”模型。#看到

  MODEL_NAME ='ssd_mobilenet_v1_coco_2017_11_17'

  MODEL_FILE = MODEL_NAME +'.tar.gz'

  DOWNLOAD_BASE =#冻结检测图的路径。这是用于对象检测的实际模型。

  PATH_TO_FROZEN_GRAPH = MODEL_NAME +'/frozen_inference_graph.pb'#用于为每个框添加正确标签的字符串列表。

  PATH_TO_LABELS = os.path.join('data','mscoco_label_map.pbtxt')

  在[5]中:

  #下载模型

  开瓶器= urllib.request.URLopener()

  opener.retrieve(DOWNLOAD_BASE + MODEL_FILE,MODEL_FILE)

  tar_file = tarfile.open(MODEL_FILE)用于tar_file.getmembers()中的文件:

  file_name = os.path.basename(file.name)

  如果文件名中的“ frozen_inference_graph.pb”:

  tar_file.extract(文件,os.getcwd())

  在[6]中:

  #将一个(冻结的)Tensorflow模型加载到内存中。

  detection_graph = tf.Graph()和detection_graph.as_default():

  od_graph_def = tf.GraphDef()

  使用tf.gfile.GFile(PATH_TO_FROZEN_GRAPH,'rb')作为fid:

  serialized_graph = fid.read()

  od_graph_def.ParseFromString(serialized_graph)

  tf.import_graph_def(od_graph_def,name ='')

  在[7]中:

  #加载标签地图#标签将地图索引映射到类别名称,这样,当我们的卷积网络预测“ 5”时,#我们知道它对应于“飞机”。在这里,我们使用内部实用程序函数,但是任何返回将整数映射到适当的字符串标签的字典的方法都可以

  category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS,use_display_name = True)

  在[8]中:

  def run_inference_for_single_image(图像,图形):

  与graph.as_default():

  与tf.Session()作为sess:

  #获取输入和输出张量的句柄

  ops = tf.get_default_graph()。get_operations()

  all_tensor_names = {ops中op的output.name在op.outputs中的输出}

  tensor_dict = {}

  用于输入[

  'num_detections','detection_boxes','detection_scores',

  'detection_classes','detection_masks']:

  张量名称=键+':0'

  如果tensor_name在all_tensor_names中:

  tensor_dict [key] = tf.get_default_graph()。get_tensor_by_name(tensor_name)

  如果tensor_dict中的'detection_masks':

  #以下处理仅适用于单个图像

  detection_boxes = tf.squeeze(tensor_dict ['detection_boxes'],[0])

  detection_masks = tf.squeeze(tensor_dict ['detection_masks'],[0])

  #需要重新框架以将蒙版从框坐标转换为图像坐标并适合图像尺寸。

  real_num_detection = tf.cast(tensor_dict ['num_detections'] [0],tf.int32)

  detection_boxes = tf.slice(detection_boxes,[0,0],[real_num_detection,-1])

  detection_masks = tf.slice(detection_masks,[0,0,0],[real_num_detection,-1,-1])

  detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(

  detection_masks,detection_boxes,image.shape [1],image.shape [2])

  detection_masks_reframed = tf.cast(

  tf.greater(detection_masks_reframed,0.5),tf.uint8)

  #遵循惯例,重新添加批次尺寸

  tensor_dict ['detection_masks'] = tf.expand_dims(

  detection_masks_reframed,0)

  image_tensor = tf.get_default_graph()。get_tensor_by_name('image_tensor:0')

  #运行推断

  output_dict = sess.run(tensor_dict,feed_dict = {image_tensor:image})

  #所有输出均为float32 numpy数组,因此请适当转换类型

  output_dict ['num_detections'] = int(output_dict ['num_detections'] [0])

  output_dict ['detection_classes'] = output_dict [

  'detection_classes'] [0] .astype(np.int64)

  output_dict ['detection_boxes'] = output_dict ['detection_boxes'] [0]

  output_dict ['detection_scores'] = output_dict ['detection_scores'] [0]

  如果output_dict中的“ detection_masks”:

  output_dict ['detection_masks'] = output_dict ['detection_masks'] [0]

  返回output_dict

  在[8]中:

  导入cv2

  cam = cv2.cv2.VideoCapture(0)

  滚动= Truewhile(滚动):

  ret,image_np = cam.read()

  image_np_expanded = np.expand_dims(image_np,axis = 0)

  #实际检测。

  output_dict = run_inference_for_single_image(image_np_expanded,detection_graph)

  #可视化检测结果。

  vis_util.visualize_boxes_and_labels_on_image_array(

  image_np

  output_dict ['detection_boxes'],

  output_dict ['detection_classes'],

  output_dict ['detection_scores'],

  category_index,

  instance_masks = output_dict.get('detection_masks'),

  use_normalized_coordinates =是,

  line_thickness = 8)

  cv2.imshow('image',cv2.resize(image_np,(1000,800)))

  如果cv2.waitKey(25)和0xFF == ord('q'):

  打破

  cv2.destroyAllWindows()

  cam.release()

  以上即是关于Python实时对象检测入门指南的全部内容,想了解更多更多关于Python的信息,请继续关注中培伟业。

标签: Python 软件研发