前言
这篇文章主要讲一下opencv怎么调用已经训练好的模型。对于不懂tensorflow,只想调用tensorflow已经训练好模型的朋友来讲非常有用。
下载链接:
.configs文件下载
.pb文件下载
.pbtxt文件下载
转换脚本下载:
tf_text_graph_faster_rcnn.py
tf_text_graph_mask_rcnn.py
tf_text_graph_ssd.py
必须明白
opencv调用tensorflow的预训练模型需要.pb文件和.pbtxt文件。
如果从上面的链接可以找到.pb文件对应的.pbtxt文件,那直接下载就好了。万一找不到也没关系,opencv提供了相应的转换脚本来从.pb转成.pbtxt文件,脚本文件名为tf_text_graph_faster_rcnn.py,tf_text_graph_mask_rcnn.py,tf_text_graph_ssd.py。
用脚本生成pbtxt文件不仅要输入pb文件,还需要输入对应的.config文件。
- 转换命令:
python tf_text_graph_ssd.py --input /path/to/model.pb --config /path/to/example.config --output /path/to/graph.pbtxt
调用
直接上代码
import cv2 as cv
cvNet = cv.dnn.readNetFromTensorflow('frozen_inference_graph.pb', 'graph.pbtxt')
img = cv.imread('example.jpg')
rows = img.shape[0]
cols = img.shape[1]
cvNet.setInput(cv.dnn.blobFromImage(img, size=(300, 300), swapRB=True, crop=False))
cvOut = cvNet.forward()
for detection in cvOut[0,0,:,:]:
score = float(detection[2])
if score > 0.3:
left = detection[3] * cols
top = detection[4] * rows
right = detection[5] * cols
bottom = detection[6] * rows
cv.rectangle(img, (int(left), int(top)), (int(right), int(bottom)), (23, 230, 210), thickness=2)
cv.putText(img, str(score), (int(right), int(bottom)), cv.FONT_HERSHEY_SIMPLEX, 1, (23, 230, 210), 2)
cv.imshow('img', img)
cv.waitKey()