Opencv&Tensorflow DNN
Posted hwanglei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Opencv&Tensorflow DNN相关的知识,希望对你有一定的参考价值。
import numpy as np
import tensorflow as tf
import cv2
###导入图像为numpy数组
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)
###视频帧提取
camera = cv2.VideoCapture(‘/path/to/video‘)
res,frame = camera.read()
#res:True or False;frame:image
###
detection_graph = tf.Graph()
with detection_graph.as_default():#打开一个图
graph_def = tf.GraphDef()#初始化
with tf.gfile.GFile(‘path/to/pd‘, ‘rb‘) as pd:#读取pb文件命名为fid
serialized_graph = pd.read() #read 为serialized_graph连载图片
graph_def.ParseFromString(serialized_graph) #从字符解析连载图片
tf.import_graph_def(graph_def, name=‘‘) #输入解析后的图片数据
###
with detection_graph.as_default():
config = tf.ConfigProto()#
config.gpu_options.allow_growth = True
with tf.Session(graph=detection_graph, config=config) as sess:
frames = 帧数;
while frames:
frames -= 1
res, frame = camera.read()#读取视屏每一帧图片
if res == 0:#读取错误,退出
break
if out is None:
[height, width] = image.shape[:2]
out = cv2.VideoWriter("./foo.avi",0,25.0,(width,height))
#输出文件名.avi(<20G);格式mp4.2或其它;帧频25.0;(宽和高)
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
#将BGR图片convert为RGB文件(red,green,blue)
image_rgb_expanded = np.expand_dims(image_rgb, axis=0)
#np.array[1,2]=>np.array[[1,2]]
###
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‘)
###
t0= time.time()
(boxes, scores, classes, num_detections) = sess.run([boxes, scores, classes, num_detections],feed_dict={image_tensor: image_np_expanded})
t = time.time() - t0
print(‘time cost: {}‘.format(t))
print(boxes.shape, boxes)
print(scores.shape,scores)
print(classes.shape,classes)
print(num_detections)
以上是关于Opencv&Tensorflow DNN的主要内容,如果未能解决你的问题,请参考以下文章
将 TensorFlow Frozen Inference Graph 加载到 OpenCV DNN 时出错
如何从 .pb 文件为 opencv 中的 dnn 模块生成 .pbtxt 文件?