Reputation: 457
I am working on a project that involves face detection, face recognition (based on facenet), age/gender detection, and face expression analysis. For each mentioned feature, I have one tensorflow graph that works fine. Now, I need to combine all of them in one single code. My approach is as follow:
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()
.....
Now my issue is that the code is not efficient and very slow. The reason is that for each frame of the video, I need to load (restore) several graphs from my disk (in while). But, I would like to load all the graphs once (before while), and just switch the graphs in the while loop to reduce the runtime. I would appreciate your comment
Upvotes: 2
Views: 1303
Reputation: 20214
Try the following form:
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)
If you want to use gpu, be careful about your gpu memory allocation.
First, one session one graph.
Second, to specify which graph operation should use:
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])
Further, when you run output_face_detection = tf.matmul(x, y)
, you just create a node and add it into a graph without any actual calculation. So you can build all your graphs first, and then use sess_xxx.run(operation)
in the loop.
Upvotes: 2