Skip to main content
 首页 » 编程设计

python之在 tensorflow 中的图形之间切换

2024年10月01日36yxwkf

我正在从事一个涉及人脸检测、人脸识别(基于 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 循环中切换图形以减少运行时间。我会很感激你的评论

请您参考如下方法:

试试下面的形式:

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) 

如果你想使用 gpu,请注意你的 gpu 内存分配。

更新

首先,一个 session 一个图表。

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

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)。