TensorFlow目标检测环境搭建与测试步骤:
第一步:安装配置环境,参考:
https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md
第二步:下载模型、配置文件与代码,下载地址:
链接:https://pan.baidu.com/s/1cbcHRyrN8SvtyvzpQsUV-w
提取码:v5r5
第三步:修改pb模型和pbtxt配置文件路径进行测试,代码如下:
test_object_detection_config.py(上述链接中包含)
import cv2
import tensorflow as tf
import numpy as np
from utils import label_map_util
from utils import visualization_utils as vis_util
#import os
#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_FROZEN_GRAPH = './model/frozen_inference_graph_faster_rcnn.pb'
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = ('./model/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_FROZEN_GRAPH, '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)
categorys = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,
use_display_name=True)
categorys_index = label_map_util.create_category_index(categorys)
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
with detection_graph.as_default():
with tf.Session(graph=detection_graph,config=config) as sess:
image = cv2.imread("./many_cars.jpg")
image_np_expanded = np.expand_dims(image, 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')
(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.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
categorys_index,
min_score_thresh=0.5,
use_normalized_coordinates=True,
line_thickness=4
)
cv2.imshow("object_detection", image)
cv2.imwrite("result.jpg", image)
cv2.waitKey(0)
测试效果(faster_rcnn_resnet50 与 ssd_mobilenet_v1_coco):
① ssd_mobilenet_v1_coco_2018_01_28
② faster_rcnn_resnet50_coco_2018_01_28
关注【OpenCV与AI深度学习】