【天天向上】OpenVINO学习笔记(四)目标检测模型

2020-06-184804
精华项目
AI 快速预览详细 收起
本文介绍了如何使用ssd_mobilenet_v2_coco目标检测模型。首先从GitHub下载模型文件,然后使用TensorFlow或OpenCV恢复模型。通过TensorFlow,可以读取并解析frozen_inference_graph.pb文件,运行模型并对图像进行目标检测。如果电脑没有TensorFlow,可以使用OpenCV加载模型,通过tf_text_graph_ssd.py脚本生成pbtxt文件,再使用cv.dnn.readNetFromTensorflow加载模型并进行前向推理。最终,可以在图像中绘制出检测到的目标框。
【模型下载】首先,我们需要下载模型文件。进入 models , 选择下载 ssd_mobilenet_v2_coco 模型文件。
【天天向上】OpenVINO学习笔记(四)目标检测模型图1
tensorflow
一般我们恢复模型都是要用到tensorflow,大致代码如下所示:
  1. import numpy as np
  2. import tensorflow as tf
  3. import cv2 as cv
  4. # Read the graph.
  5. with tf.gfile.FastGFile('frozen_inference_graph.pb', 'rb') as f:
  6.     graph_def = tf.GraphDef()
  7.     graph_def.ParseFromString(f.read())
  8. with tf.Session() as sess:
  9.     # Restore session
  10.     sess.graph.as_default()
  11.     tf.import_graph_def(graph_def, name='')
  12.     # Read and preprocess an image.
  13.     img = cv.imread('example.jpg')
  14.     rows = img.shape[0]
  15.     cols = img.shape[1]
  16.     inp = cv.resize(img, (300, 300))
  17.     inp = inp[:, :, [2, 1, 0]]  # BGR2RGB
  18.     # Run the model
  19.     out = sess.run([sess.graph.get_tensor_by_name('num_detections:0'),
  20.                     sess.graph.get_tensor_by_name('detection_scores:0'),
  21.                     sess.graph.get_tensor_by_name('detection_boxes:0'),
  22.                     sess.graph.get_tensor_by_name('detection_classes:0')],
  23.                    feed_dict={'image_tensor:0': inp.reshape(1, inp.shape[0], inp.shape[1], 3)})
  24.     # Visualize detected bounding boxes.
  25.     num_detections = int(out[0][0])
  26.     for i in range(num_detections):
  27.         classId = int(out[3][0])
  28.         score = float(out[1][0])
  29.         bbox = [float(v) for v in out[2][0]]
  30.         if score > 0.3:
  31.             x = bbox[1] * cols
  32.             y = bbox[0] * rows
  33.             right = bbox[3] * cols
  34.             bottom = bbox[2] * rows
  35.             cv.rectangle(img, (int(x), int(y)), (int(right), int(bottom)), (125, 255, 51), thickness=2)
  36. cv.imshow('TensorFlow MobileNet-SSD', img)
  37. cv.waitKey()
复制代码

【opencv】
如果电脑没有tensorflow想要恢复模型怎么办?那就可以考虑下opencv了,opencv加载tensorflow模型需要pb文件和pbtxt文件,pbtxt是可以根据pb文件生成的,在opencv的源代码中进入sample/dnn 文件夹中,由于我们的模型是ssd因此找到以下两个文件

tf_text_graph_ssd.py
tf_text_graph_common.py
https://github.com/opencv/opencv,中的 opencv-master\samples\dnn中找到
【天天向上】OpenVINO学习笔记(四)目标检测模型图3
在命令行执行

python tf_text_graph_ssd.py --input C:\Users\zlzx\Downloads\ssd_mobilenet_v2_coco_2018_03_29\frozen_inference_graph.pb --config C:\Users\zlzx\Downloads\ssd_mobilenet_v2_coco_2018_03_29\pipeline.config --output frozen_inference_graph.pbtxt
frozen_inference_graph.pb是下载的训练pb模型,pipeline是训练时的配置文件,生成pb时会有,frozen_inference_graph.pbtxt就是生成的文件用于opencv恢复模型

然后用opencv恢复模型

net = cv2.dnn.readNetFromTensorflow(weightsPath,configPath)

大致代码如下:

  1. import cv2 as cv
  2. cvNet = cv.dnn.readNetFromTensorflow('frozen_inference_graph.pb', 'frozen_inference_graph.pbtxt')
  3. img = cv.imread('example.jpg')
  4. rows = img.shape[0]
  5. cols = img.shape[1]
  6. cvNet.setInput(cv.dnn.blobFromImage(img, size=(300, 300), swapRB=True, crop=False))
  7. cvOut = cvNet.forward()
  8. for detection in cvOut[0,0,:,:]:
  9.     score = float(detection[2])
  10.     if score > 0.3:
  11.         left = detection[3] * cols
  12.         top = detection[4] * rows
  13.         right = detection[5] * cols
  14.         bottom = detection[6] * rows
  15.         cv.rectangle(img, (int(left), int(top)), (int(right), int(bottom)), (23, 230, 210), thickness=2)
  16. cv.imshow('img', img)
  17. cv.waitKey()
复制代码

【天天向上】OpenVINO学习笔记(四)目标检测模型图2



注:Tensorflow模型的graph结构可以保存为.pb文件或者.pbtxt文件,或者.meta文件,其中只有.pbtxt文件是可读的。在OpenCV中,每个模型.pb文件,原则上应有一个对应的文本图形定义的.pbtxt文件,当然也可能没有,在opencv_extra\testdata\dnn有些.pbtxt文件是可以对应找到,这个要看opencv会不会提供。

创作许可协议

本项目采用 None(不开放任何权利,保留所有权利) 进行许可。

评论(0)
- 没有更多了 -

创作许可协议

本项目采用 None(不开放任何权利,保留所有权利) 进行许可。

相关推荐