Tensorflow物体检测(ObjectDetection)API的使用

Tensorflow物体检测(ObjectDetection)API的使⽤Tensorflow在更新1.2版本之后多了很多新功能,其中放出了很多⽤tf框架写的深度⽹络结构(看),⼤⼤降低了吾等调包侠的开发难度,⽆
冷光源uv机论是fine-tuning还是该⽹络结构都⽅便了不少。这⾥讲的的是物体检测(object detection)API,这个库的很详细,可以的话直接看原⽂即可。
这个物体检测API提供了5种⽹络结构的预训练的weights,全部是⽤集进⾏训练,可以在下载:分别是SSD+mobilenet, SSD+inception_v2, R-FCN+resnet101, faster RCNN+resnet101, faster RCNN+inception+resnet101。各个模型的精度和计算所需时间如下,具体测评细节可以看:
依赖包
Protobuf 2.6
Pillow 1.0
lxml
tf Slim
Jupyter notebook
Matplotlib  # ⽤这个画图会⽐较慢,内存占⽤⾼,可以⽤cv2来代替
Tensorflow
API安装
$ pip install tensorflow-gpu
$ sudo apt-get install protobuf-compiler python-pil python-lxml
$ sudo pip install jupyter
$ sudo pip install matplotlib
因为使⽤protobuf来配置模型和训练参数,所以API正常使⽤必须先编译protobuf库:
$ cd tensorflow/models
$ protoc object_detection/protos/*.proto --python_out=.
然后将models和slim(tf⾼级框架)加⼊python环境变量:
export PYTHONPATH=$PYTHONPATH:/your/path/to/tensorflow/models:/your/path/to/tensorflow/models/slim
最后测试安装:
python object_detection/builders/model_builder_test.py
fine-tuning
1.
自动扶梯装饰
以Pascal VOC数据集的格式为例:object_detection/create_pascal_tf_record.py提供了⼀个,将voc格式的数据保存到.record格式
python object_detection/create_pascal_tf_record.py \延时冲洗阀
--label_map_path=object_detection/data/pascal_label_map.pbtxt \  # 训练物品的品类和id
--data_dir=VOCdevkit --year=VOC2012 --set=train \
--output_path=d
python object_detection/create_pascal_tf_record.py \
--label_map_path=object_detection/data/pascal_label_map.pbtxt \
--data_dir=VOCdevkit --year=VOC2012 --set=val \
--output_path=d
其中--data_dir为训练集的⽬录。结构同Pascal VOC,如下:
+ VOCdevkit  # +为⽂件夹
+ JPEGImages
- 001.jpg  # - 为⽂件
+ Annotations
- l
2.
train和eval输⼊输出数据储存结构为:
+ input
- label_map.pbtxt file  # 可以在object_detection/data/*.pbtxt到样例
- train TFRecord file
- eval TFRecord file
+ models索道安装
+ modelA
- pipeline config file # 可以在object_detection/samples/configs/*.config下到样例,定义训练参数和输⼊数据
+ train  # 保存训练产⽣的checkpoint⽂件
+ eval
准备好上述⽂件后就可以直接调⽤进⾏训练
python object_detection/train.py \
--logtostderr \
--pipeline_config_path=/your/path/to/models/modelA/pipeline config file \
--train_dir=/your/path/to/models/modelA/train当铺网
3. 评估
在训练开始以后,就可以运⾏eval来评估模型的效果。不过实际情况是eval模型也需要加载ckpt⽂件,因此也需要占⽤不⼩的显存,⽽⼀般训练的时候都会调整batch尽量利⽤显卡性能,所以想要实时运⾏train和eval的话需要调整好两者所需的内存。
python object_detection/eval.py \
--logtostderr \
--pipeline_config_path=/your/path/to/models/modelA/pipeline config file \
--checkpoint_dir=/your/path/to/models/modelA/train \
--eval_dir=/your/path/to/models/modelA/eval
4. 监控
通过tensorboard命令可以在浏览器很轻松的监控训练进程,在浏览器输⼊localhost:6006(默认)即可
tensorboard --logdir=/your/path/to/models/modelA  # 需要包含eval和train⽬录(.ckpt, .index, .meta, checkpoint, graph.pbtxt⽂件)
freeze model
在训练完成后需要将训练产⽣的最后⼀组.meta, .index, .ckpt, checkpoint⽂件。其中meta保存了graph和metadata,ckpt保存了⽹络的weights。⽽在⽣产环境中进⾏预测的时候是只需要模型和权重,不需要metadata,所以需要将其提出进⾏freeze操作,将所需的部分放到⼀个⽂件,⽅便之后的调⽤,也减少模型加载所需的内存。(在下载的预训练模型解压后可以到4个⽂件,其中名为
frozen_inference_graph.pb的⽂件就是freeze后产⽣的模型⽂件,⽐weights⽂件⼤,但是⽐weights和meta⽂件加起来要⼩不少。)
本来,tensorflow/python/tools/freeze_graph.py提供了freeze model的api,但是需要提供输出的final node names(⼀般是softmax之类的最后⼀层的激活函数命名),⽽object detection api提供提供了预训练好的⽹络,final node name并不好,所以object_detection⽬录下还提供
了export_inference_graph.py。
python export_inference_graph.py \
--input_type image_tensor \
--pipeline_config_path /your/path/to/models/modelA/pipeline config file \
--checkpoint_path  /your/path/to/models/modelA/train/model.ckpt-* \
--inference_graph_path /your/path/to/models/modelA/train/frozen_inference_graph.pb  # 输出的⽂件名
模型调⽤
⽬录下提供了⼀个。这⾥只是稍作调整⽤cv2来显⽰图像。
import numpy as np
import os, sys
import tensorflow as tf
import cv2
MODEL_ROOT = "/home/arkenstone/tensorflow/workspace/models"
sys.path.append(MODEL_ROOT)  # 应⽤和训练的⽬录在不同的地⽅
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
MODEL_PATH = "/home/arkenstone/tensorflow/workspace/models/objectdetection/models/faster_rcnn_inception_resnet_v2_atrous_coco_11_06_2017"
PATH_TO_CKPT = MODEL_PATH + '/frozen_inference_graph.pb'  # frozen model path
PATH_TO_LABELS = os.path.join(MODEL_ROOT, 'object_detection/data', 'mscoco_label_map.pbtxt')
细胞核染
NUM_CLASSES = 90
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_vert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_ate_category_index(categories)  # 格式为{1:{'id': 1, 'name': 'person'}, 2: {'id': 2, 'name': 'bicycle'}, ...}
# 模型加载:test.py
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 = ad()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
# 防⽌内存不⾜,限制sess内存使⽤⽐例
gpu_memory_fraction = 0.4
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
config = tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False, allow_soft_placement=True) config.gpu_options.allow_growth = False
def detect(image_path):
with detection_graph.as_default():  # 需要⼿动close sess
with tf.Session(graph=detection_graph, config=config) as sess:
image = cv2.imread(image_path)
image_np = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image_np_expanded = np.expand_dims(image_np, axis=0)
image_tensor = _tensor_by_name('image_tensor:0')
boxes = _tensor_by_name('detection_boxes:0')
scores = _tensor_by_name('detection_scores:0')
classes = _tensor_by_name('detection_classes:0')
num_detections = _tensor_by_name('num_detections:0')
(boxes, scores, classes, num_detections) = sess.run(
[boxes, scores, classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
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)
new_img = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
cv2.imshow("test", new_img)
cv2.waitKey(0)
if __name__ == '__main__':
detect(/your/test/image)
参考

本文发布于:2024-09-21 16:44:11,感谢您对本站的认可!

本文链接:https://www.17tex.com/tex/2/214850.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:训练   模型   需要   所需   内存   提供   调包   数据
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议