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)

猜你喜欢

转载自www.cnblogs.com/hwanglei/p/9346604.html
DNN