使用tensorflow object detection API实现目标检测

2024-06-17 13:58

本文主要是介绍使用tensorflow object detection API实现目标检测,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

环境

Windows7 x64
conda 4.3.30

1、TensorFlow安装

首先在conda中创建TensorFlow环境

conda create -n tensorflow python=3.6.2

激活tensorflow环境

activate tensorflow

安装tensorflow

pip install tensorflow==1.12.0

安装完成后会在anaconda安装路径envs文件下自动创建tensorflow目录
在这里插入图片描述

2、tensorflow object detection API安装

下载安装包:https://github.com/xizhonghuai/tensorflow_object_detection_demo
在这里插入图片描述
下载完成后解压,将tensorflow_models文件夹拷贝到不含中文任意路径下,如:
在这里插入图片描述
在anaconda安装路径下找到刚才新创建的tensorflow环境目录
在这里插入图片描述
在\Lib\site-packages下创建tensorflow_model.pth文件,内容如下:

E:\python\workspace\tensorflow_models\research
E:\python\workspace\tensorflow_models\research\slim

进入E:\python\workspace\tensorflow_models\research\slim文件夹下分别执行一下命令:

python setup.py build 
python setup.py install

运行后如果出现error: could not create ‘build’,请删掉\slim文件夹下BUILD文件,在重新执行。

进入E:\python\workspace\tensorflow_models\research文件夹下分别执行一下命令:

python setup.py build 
python setup.py install

这个过程时间稍长,若出现报错情况,请仔细查看报错信息是否提示缺少相关依赖,手动通过pip安装。

测试tensorflow object detection API是否安装成功,在E:\python\workspace\tensorflow_models\research下执行

object_detection/builders/model_builder_test.py

无报错表示安装成功。

说明:
报错信息提示找不到相关模块,请卸载tensorflow,重新安装其他版本。
报错信息提示DLL相关错误,请卸载tensorflow,在以下链接中安装 https://github.com/fo40225/tensorflow-windows-wheel

3、测试

下载官方已训练好的模型到本地,这里我们使用ssd_mobilenet_v1_coco(模型包含90种常见物体的识别)
https://github.com/xizhonghuai/tensorflow_object_detection_demo/blob/master/tensorflow_models/research/object_detection/g3doc/detection_model_zoo.md

在这里插入图片描述
点击下载ssd_mobilenet_v1_coco模型你解压到本地。

打开iead,创建python工程,创建com包,在com包下分别创建,data、test_images、model文件夹

将刚才解压模型包中的frozen_inference_graph.pb文件拷贝到model文件下。

在E:\python\workspace\tensorflow_models\research\object_detection\data_back_up文件夹下拷贝mscoco_label_map.pbtxt文件到data文件下。

在网上随便找一张图片重命名为image1.jpg存放到test_images下

项目结构如下:
在这里插入图片描述

在com包下创建py代码:

import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfilefrom collections import defaultdict
from io import StringIO
# from matplotlib import pyplot as plt
from PIL import Image
## Env setup
# This is needed to display the images.# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")from object_detection.utils  import label_map_util
from object_detection.utils  import visualization_utils as vis_utilos.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"# Model preparation
## Variables#Any model exported using the `export_inference_graph.py` tool can be loaded here #simply by changing `PATH_TO_CKPT` to point to a new .pb file.
#By default we use an "SSD with Mobilenet" model here. See the [detection model zoo](https://github.com/tensorflow/models/blob/master/object_detection/g3doc/detection_mo#del_zoo.md) for a list of other models that can be run out-of-the-box with varying #speeds and accuracies.# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = 'model/frozen_inference_graph.pb'PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')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:print(PATH_TO_CKPT)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)## 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)# Detection
# For the sake of simplicity we will use only 2 images:
# image1.jpg
# image2.jpg
# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
PATH_TO_TEST_IMAGES_DIR = 'test_images'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 2) ]
#TEST_IMAGE_PATHS = ['test_images']
# Size, in inches, of the output images.
IMAGE_SIZE = (12, 8)with detection_graph.as_default():with tf.Session(graph=detection_graph) as sess:for image_path in TEST_IMAGE_PATHS:image = Image.open(image_path)# the array based representation of the image will be used later in order to prepare the# result image with boxes and labels on it.image_np = load_image_into_numpy_array(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)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)# plt.figure(figsize=IMAGE_SIZE)            # plt.imshow(image_np)# plt.show()im = Image.fromarray(image_np)im.save("ret.jpeg")
print("OK")

测试:

执行python代码,运行成功后将生成识别结果并保存图片到com包下。
在这里插入图片描述

在这里插入图片描述

这篇关于使用tensorflow object detection API实现目标检测的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

C语言中联合体union的使用

本文编辑整理自: http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=179471 一、前言 “联合体”(union)与“结构体”(struct)有一些相似之处。但两者有本质上的不同。在结构体中,各成员有各自的内存空间, 一个结构变量的总长度是各成员长度之和。而在“联合”中,各成员共享一段内存空间, 一个联合变量

Tolua使用笔记(上)

目录   1.准备工作 2.运行例子 01.HelloWorld:在C#中,创建和销毁Lua虚拟机 和 简单调用。 02.ScriptsFromFile:在C#中,对一个lua文件的执行调用 03.CallLuaFunction:在C#中,对lua函数的操作 04.AccessingLuaVariables:在C#中,对lua变量的操作 05.LuaCoroutine:在Lua中,

Vim使用基础篇

本文内容大部分来自 vimtutor,自带的教程的总结。在终端输入vimtutor 即可进入教程。 先总结一下,然后再分别介绍正常模式,插入模式,和可视模式三种模式下的命令。 目录 看完以后的汇总 1.正常模式(Normal模式) 1.移动光标 2.删除 3.【:】输入符 4.撤销 5.替换 6.重复命令【. ; ,】 7.复制粘贴 8.缩进 2.插入模式 INSERT

Lipowerline5.0 雷达电力应用软件下载使用

1.配网数据处理分析 针对配网线路点云数据,优化了分类算法,支持杆塔、导线、交跨线、建筑物、地面点和其他线路的自动分类;一键生成危险点报告和交跨报告;还能生成点云数据采集航线和自主巡检航线。 获取软件安装包联系邮箱:2895356150@qq.com,资源源于网络,本介绍用于学习使用,如有侵权请您联系删除! 2.新增快速版,简洁易上手 支持快速版和专业版切换使用,快速版界面简洁,保留主

如何免费的去使用connectedpapers?

免费使用connectedpapers 1. 打开谷歌浏览器2. 按住ctrl+shift+N,进入无痕模式3. 不需要登录(也就是访客模式)4. 两次用完,关闭无痕模式(继续重复步骤 2 - 4) 1. 打开谷歌浏览器 2. 按住ctrl+shift+N,进入无痕模式 输入网址:https://www.connectedpapers.com/ 3. 不需要登录(也就是

通过高德api查询所有店铺地址信息

通过高德api查询所有店铺地址电话信息 需求:通过高德api查询所有店铺地址信息需求分析具体实现1、申请高德appkey2、下载types city 字典值3、具体代码调用 需求:通过高德api查询所有店铺地址信息 需求分析 查询现有高德api发现现有接口关键字搜索API服务地址: https://developer.amap.com/api/webservice/gui

DDei在线设计器-API-DDeiSheet

DDeiSheet   DDeiSheet是代表一个页签,一个页签含有一个DDeiStage用于显示图形。   DDeiSheet实例包含了一个页签的所有数据,在获取后可以通过它访问其他内容。DDeiFile中的sheets属性记录了当前文件的页签列表。   一个DDeiFile实例至少包含一个DDeiSheet实例。   本篇最后提供的示例可以在DDei文档直接预览 属性 属性名说明数

Toolbar+DrawerLayout使用详情结合网络各大神

最近也想搞下toolbar+drawerlayout的使用。结合网络上各大神的杰作,我把大部分的内容效果都完成了遍。现在记录下各个功能效果的实现以及一些细节注意点。 这图弹出两个菜单内容都是仿QQ界面的选项。左边一个是drawerlayout的弹窗。右边是toolbar的popup弹窗。 开始实现步骤详情: 1.创建toolbar布局跟drawerlayout布局 <?xml vers

C#中,decimal类型使用

在Microsoft SQL Server中numeric类型,在C#中使用的时候,需要用decimal类型与其对应,不能使用int等类型。 SQL:numeric C#:decimal

探索Elastic Search:强大的开源搜索引擎,详解及使用

🎬 鸽芷咕:个人主页  🔥 个人专栏: 《C++干货基地》《粉丝福利》 ⛺️生活的理想,就是为了理想的生活! 引入 全文搜索属于最常见的需求,开源的 Elasticsearch (以下简称 Elastic)是目前全文搜索引擎的首选,相信大家多多少少的都听说过它。它可以快速地储存、搜索和分析海量数据。就连维基百科、Stack Overflow、