之前写过一篇直接读取模型输出检测结果的文章
https://blog.csdn.net/qq_36501182/article/details/87919038
后来发现OpenCV 3.4.1之后的版本中contrib扩展库中的dnn模块支持TensorFlow、Caffe、Pytorch三种深度学习框架的模型,能够修改或者读取网络结构,并且也能够读取已经训练好的模型。
实例如下:
import cv2 as cv
#cvNet = cv.dnn.readNetFromTensorflow('frozen_inference_graph.pb', 'graph.pbtxt')
cvNet = cv.dnn.readNetFromTensorflow('frozen_inference_graph.pb')
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])
print("looping here score ", score)
if score > 0.5:
print("get stuff looping here ")
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.imshow('img', img)
cv.waitKey()
具体参考官网说明:https://github.com/opencv/opencv/wiki/TensorFlow-Object-Detection-API