2017-09-06 76 views
0

我正在研究一个涉及人脸检测,人脸识别(基于facenet),年龄/性别检测和人脸表情分析的项目。对于每个提到的功能,我有一个正常工作的tensorflow图。现在,我需要将它们全部结合在一个代码中。我的做法如下:在张量流图之间切换

with tf.Graph().as_default(): 

     sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False)) 
     with sess.as_default(): 

      #configure my camera 
      video_capture = cv2.VideoCapture(0) 


      while True: 

       #read one frame from camera 
       ret, frame = video_capture.read() 



      #here I load face recognition graph using saver restore 
      facenet.load_model(modeldir) 
      images_placeholder tf.get_default_graph().get_tensor_by_name("input:0") 
      embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0") 


      #Here I reset the graph and load another tensorflow graph for age/gender detection 
      tf.reset_default_graph() 
      .... 


      #Here I reset the graph and load another tensorflow graph for face expression analysis 
      tf.reset_default_graph() 
      ..... 

现在我的问题是代码效率不高,速度很慢。原因是对于视频的每一帧,我需要从我的磁盘加载(恢复)几张图(在while中)。但是,我想一次加载所有图形(在while之前),只需在while循环中切换图形以减少运行时间。如果你想利用GPU,小心你的GPU内存分配

graph_face_detection = tf.Graph() 
sess_face_detection = tf.Session(graph=graph_face_detection) 

graph_face_recognition = tf.Graph() 
sess_face_recognition = tf.Session(graph=graph_face_recognition) 

... 

sess_face_detection.run(operations) 

... 

sess_face_recognition.run(operations) 

:我很感激您的评论

回答

0

尝试以下表格。

更新

首先,一个会话一个图。

二,指定哪个图形操作应该使用:

graph_face_detection = tf.Graph() 
sess_face_detection = tf.Session(graph=graph_face_detection) 

graph_face_recognition = tf.Graph() 
sess_face_recognition = tf.Session(graph=graph_face_recognition) 

with graph_face_detection.as_default() as g: 
    output_face_detection = tf.matmul(x, y) 

with graph_face_recognition.as_default() as g: 
    output_face_recognition = tf.matmul(x, y) 

... 

sess_face_detection.run([output_face_detection]) 
sess_face_recognition.run([output_face_recognition]) 

此外,当您运行output_face_detection = tf.matmul(x, y),您只需创建一个节点,并将其添加成图形,没有任何实际的计算。因此,您可以先创建所有图形,然后在循环中使用sess_xxx.run(operation)

+0

谢谢。假设我在代码“softmax_output = tf.nn.softmax(logits)”中添加了这样的一行,我想知道它属于哪个会话和图表?我可以强制系统将它添加到上述会话/图表之一中吗? – user2867237

+0

还有一个问题:我可以将所有图形添加到1个会话吗?还是对于每个图表,我需要创建一个会话?谢谢 – user2867237

+0

@ user2867237我编辑我的答案。 – Sraw